Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize this Xml in .NET (array)

I need Xml that looks like this

<foo>
  <bar ... />
  <bar ... />
</foo>

And currently have the following class structure :

[XmlRoot("foo")]
public class Foo
{
  [XmlArrayItem("bar")]
  public List<Bar> myBars;
}

But this gives me Xml where bar items are wrapped inside a bars element. How should I define my custom XmlAttributes so I'd get the Xml structure I need?

like image 752
Morri Avatar asked May 28 '10 10:05

Morri


People also ask

What is XML serialization in C#?

XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport. Deserialization re-creates the object in its original state from the XML output.

What is serializing XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.


2 Answers

I had to solve something similar yesterday, and this was the solution for me:

[XmlRoot("foo")]
public class Foo
{
    [XmlElement("bar")]
    public List<Bar> myBars;
}
like image 83
David M Avatar answered Sep 22 '22 07:09

David M


The solution I use is this:

[XmlRoot("foo")]
public class Foo : List<Bar>
{
}

[XmlType("bar")]
public class Bar
{
}

In fact, I defined Foo as a List<T>, so it works as a generic list. The type in that list just needs to define the XmlType attribute.

like image 29
Steven Avatar answered Sep 25 '22 07:09

Steven