GrZeCh
GrZeCh

Reputation: 2332

How do you rename the child XML elements used in an XML Serialized List<string>?

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!

Upvotes: 2

Views: 4094

Answers (3)

kgriffs
kgriffs

Reputation: 4278

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;

Upvotes: 0

Paul Sonier
Paul Sonier

Reputation: 39520

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

Upvotes: 0

user7116
user7116

Reputation: 64148

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">
  <Properties>
    <Property>test1</Property>
    <Property>test2</Property>
    <Property>test3</Property>
  </Properties>
</Program>

Upvotes: 7

Related Questions