views:

705

answers:

4

Hello, I'm serializing to XML my class where one of properties has type List<string>.

public class MyClass {
    ...
    public List<string> Properties { get; set; }
    ...
}

XML created by serializing this class looks like this:

<MyClass>
    ...
    <Properties>
        <string>somethinghere</string>
        <string>somethinghere</string>
    </Properties>
    ...
</MyClass>

and now my question. How can I change my class to achieve XML like this:

<MyClass>
    ...
    <Properties>
        <Property>somethinghere</Property>
        <Property>somethinghere</Property>
    </Properties>
    ...
</MyClass>

after serializing. Thanks for any help!

+2  A: 

Try XmlArrayItemAttribute:

using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;

public class Program
{
    [XmlArrayItem("Property")]
    public List<string> Properties = new List<string>();

    public static void Main(string[] args)
    {
        Program program = new Program();
        program.Properties.Add("test1");
        program.Properties.Add("test2");
        program.Properties.Add("test3");

        XmlSerializer xser = new XmlSerializer(typeof(Program));
        xser.Serialize(new FileStream("test.xml", FileMode.Create), program);
    }
}

test.xml:

<?xml version="1.0"?>
<Program xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  <Properties>
    <Property>test1</Property>
    <Property>test2</Property>
    <Property>test3</Property>
  </Properties>
</Program>
sixlettervariables
Great! It works. Big thanks
GrZeCh
A: 

Add [XmlElement("Property")] before the declaration of your Properties member.

McWafflestix
When I used [XmlElement("Property")] before my property XML leafs was genereted under MyClass node (they should be placed under "Properties"). Using [XmlArrayItem("Property")] solved my problem. Thanks for helping
GrZeCh
A: 

Thanks. I just had the same question.

A: 

If you want to do this in a WCF service and still use DataContractSerializer, you can simply define a new List subclass:

[CollectionDataContract(ItemName="Property")]
public class PropertyList: List<string>
{
    public PropertyList() { }
    public PropertyList(IEnumerable<string> source) : base(source) { }
}

Then, in the class you are serializing, just specify the member as:

[DataMember]
public PropertyList Properties;
Kurt