Reputation: 2332
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
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
Reputation: 39520
Add [XmlElement("Property")]
before the declaration of your Properties member.
Upvotes: 0
Reputation: 64148
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