1

i've two classes A and B. A is for the ROOT-Element and B should be an array of B.

public class A
{
    public B[] b;
}

public class B
{
    public string param1;
    public string param2;
}

Create instances and fill with data look like this:

A test = new A();
test.b = new B[2];

test.b[0] = new B();
test.b[1] = new B();

test.b[0].param1 = "b0-p1";
test.b[0].param2 = "b0-p2";
test.b[1].param1 = "b1-p1";
test.b[1].param2 = "b1-p2";

Now serialize:

System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(A));
System.IO.TextWriter wr = new System.IO.StreamWriter(@"c:\ser.xml");
ser.Serialize(wr, test);
wr.Close();

The generated XML look like this

<?xml version="1.0" encoding="utf-8"?>
<A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org /2001/XMLSchema">
  <b>
    <B>
      <param1>b0-p1</param1>
      <param2>b0-p2</param2>
    </B>
    <B>
      <param1>b1-p1</param1>
      <param2>b1-p2</param2>
    </B>
  </b>
</A>

But I want to have this:

<?xml version="1.0" encoding="utf-8"?>
<A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org /2001/XMLSchema">
  <b>
    <param1>b0-p1</param1>
    <param2>b0-p2</param2>
  </b>
  <b>
    <param1>b1-p1</param1>
    <param2>b1-p2</param2>
  </b>
</A>

Can you tell me what I'm doing wrong?

regards raiserle

1 Answer 1

2

Decorate B[] b property with XmlElementAttribute:

public class A
{
    [XmlElement("b")]
    public B[] b;
}

You'll need using System.Xml.Serialization; at the top of the file to make it work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thx, i've tested it with wrong attribute: System.Xml.Serialization.XmlArray("b") and System.Xml.Serialization.XmlArrayItem("b") Thx, thx .. thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.