Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net XML serialization: how to specify an array's root element and child element names

Consider the following serializable classes:

class Item {...}
class Items : List<Item> {...}
class MyClass
{
   public string Name {get;set;}
   public Items MyItems {get;set;}
}

I want the serialized output to look like:

<MyClass>
    <Name>string</Name>
    <ItemValues>
        <ItemValue></ItemValue>
        <ItemValue></ItemValue>
        <ItemValue></ItemValue>
    </ItemValues>
</MyClass>

Notice the element names ItemValues and ItemValue doesn't match the class names Item and Items, assuming I can't change the Item or Items class, is there any why to specify the element names I want, by modifying the MyClass Class?

like image 297
Jeremy Avatar asked Mar 19 '10 18:03

Jeremy


People also ask

What is the correct way of using XML serialization?

As with the CreatePo method, you must first construct an XmlSerializer, passing the type of the class to be deserialized to the constructor. Also, a FileStream is required to read the XML document. To deserialize the objects, call the Deserialize method with the FileStream as an argument.

Which of the following attribute controls XML serialization of the attribute target as an XML root element?

XmlRootAttribute Class (System.Xml.Serialization) Controls XML serialization of the attribute target as an XML root element.

Which class should be used to serialize an object in XML format?

Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".

How does the XmlSerializer work C#?

The XmlSerializer creates C# (. cs) files and compiles them into . dll files in the directory named by the TEMP environment variable; serialization occurs with those DLLs. These serialization assemblies can be generated in advance and signed by using the SGen.exe tool.


2 Answers

public class MyClass
{
    public string Name {get;set;}
    [XmlArray("ItemValues")]
    [XmlArrayItem("ItemValue")]
    public Items MyItems {get;set;}
}
like image 192
Marc Gravell Avatar answered Sep 28 '22 05:09

Marc Gravell


You might want to look at "How to: Specify an Alternate Element Name for an XML Stream"

That article discusses using the XmlElementAttribute's ElementName to accomplish this.

like image 43
hackerhasid Avatar answered Sep 28 '22 04:09

hackerhasid