Control XML Serialization element name

G

Guest

Hi all,
I want to control element name of a collection in XML serialization,
[Serializable()]
public class MatchedServiceItem {
[XmlArrayItem(ElementName = "ServiceList")]
public List<int[]> MatchedServiceIDs;
}

Then I get following result
<?xml version="1.0" encoding="utf-8"?>
<Setting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MatchedServiceItems>
<MatchedServiceItem>
<MatchedServiceIDs>
<ServiceList>
<int>1</int>
<int>2</int>
</ServiceList>
<ServiceList>
<int>1000</int>
</ServiceList>
</MatchedServiceIDs>
<MatchedServiceText>Match A</MatchedServiceText>
</MatchedServiceItem>
</MatchedServiceItems>
</Setting>

Now how can I furtuer control element name of int[] (nested within
List<int[]>)?

Thanks in advance!
 
M

Marc Gravell

I can't think of any neat ways that don't involve extra classes... but
perhaps reverse engineer from the desired xml via xsd and see what you
get? A quick test shows that repeated XmlArrayItem attributes with
different nest-leves might just do the trick...
 
M

Marc Gravell

Like so? (courtesy of some xsd.exe testing...)

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

[Serializable()]
public class MatchedServiceItem {
[XmlArrayItem(ElementName = "ServiceList", NestingLevel = 0)]
[XmlArrayItem(ElementName = "Val", NestingLevel = 1)]
public List<int[]> MatchedServiceIDs;


}
class Program {
static void Main(string[] args) {
MatchedServiceItem msi = new MatchedServiceItem();
msi.MatchedServiceIDs = new List<int[]>();
msi.MatchedServiceIDs.Add(new int[] { 1, 2 });
msi.MatchedServiceIDs.Add(new int[] { 1000 });

XmlSerializer ser = new
XmlSerializer(typeof(MatchedServiceItem));
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb)) {
ser.Serialize(sw, msi);
sw.Close();
}
Console.Write(sb.ToString());
Console.ReadKey();

}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top