开发者

How to use XmlSerializer to deserialize a simple collection into an instance of List<string>

I haven't been able to find a question related to m开发者_运维知识库y specific problem.

What I am trying to do is take a list of Xml nodes, and directly deserialize them to a List without having to create a class with attributes.

So the xml (myconfig.xml) would look something like this...

<collection>  
    <item>item1</item>
    <item>item2</item>
    <item>item3</item>
    <item>etc...</item>
</collection>  

In the end I would like a list of items as strings.

The code would look like this.

XmlSerializer serializer = new XmlSerializer( typeof( List<string> ) );
using (XmlReader reader = XmlReader.Create( "myconfig.xml" )
{
    List<string> itemCollection = (List<string>)serializer.Deserialize( reader );
}

I'm not 100% confident that this is possible, but I'm guessing it should be. Any help would be greatly appreciated.


Are you married to the idea of using a serializer? If not, you can try Linq-to-XML. (.NET 3.5, C# 3 [and higher])

Based on your provided XML file format, this is the simple code.

// add 'using System.Xml.Linq' to your code file
string file = @"C:\Temp\myconfig.xml";
XDocument document = XDocument.Load(file);
List<string> list = (from item in document.Root.Elements("item")
                     select item.Value)
                    .ToList();


Ok, interestingly enough I may have found half the answer by serializing an existing List.

The result I got is as follows...

This following code:

List<string> things = new List<string> { "thing1", "thing2" };
XmlSerializer serializer = new XmlSerializer(typeof(List<string>), overrides);
using (TextWriter textWriter = new StreamWriter("things.xml"))
{
    serializer.Serialize(textWriter, things);
}

Outputs a result of:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <string>thing1</string>
    <string>thing2</string>
</ArrayOfString>

I can override the root node by passing an XmlAttributeOverrides instance to the second parameter of the XmlSerializer constructor. It is created like this:

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attributes = new XmlAttributes { XmlRoot = new XmlRootAttribute("collection") };
overrides.Add( typeof(List<string>), attributes );

This will change "ArrayOfString" to "collection". I still have not figured out how to control the name of the string element.


To customize List element names using XmlSerializer, you have to wrap the list.

[XmlRoot(Namespace="", ElementName="collection")]
public class ConfigWrapper
{
    [XmlElement("item")]
    public List<string> Items{ get; set;}
}

Usage:

   var itemsList = new List<string>{"item1", "item2", "item3"};
   var cfgIn = new ConfigWrapper{ Items = itemsList };
   var xs = new XmlSerializer(typeof(ConfigWrapper));
   string fileContent = null;

   using (var sw = new StringWriter())
   {
        xs.Serialize(sw, cfgIn);
        fileContent = sw.ToString();
        Console.WriteLine (fileContent);
   }

   ConfigWrapper cfgOut = null;
   using (var sr = new StringReader(fileContent))
   {
        cfgOut = xs.Deserialize(sr) as ConfigWrapper;
        // cfgOut.Dump(); //view in LinqPad
        if(cfgOut != null)
            // yields 'item2'
            Console.WriteLine (cfgOut.Items[1]);
   }

Output:

// fileContent:
<?xml version="1.0" encoding="utf-16"?>
<collection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <item>item1</item>
  <item>item2</item>
  <item>item3</item>
</collection>

If you don't want to wrap the list, the DataContractSerializer will allow you to custom name the elements if you subclass it:

[CollectionDataContract(Name = "collection", ItemName = "item", Namespace = "")]
public class ConfigWrapper : List<string>
{
    public ConfigWrapper() : base() { }
    public ConfigWrapper(IEnumerable<string> items) : base(items) { }
    public ConfigWrapper(int capacity) : base(capacity) { }
}

Usage And Output:

   var cfgIn = new ConfigWrapper{ "item1", "item2", "item3" };
   var ds = new DataContractSerializer(typeof(ConfigWrapper));
   string fileContent = null;

   using (var ms = new MemoryStream())
   {
        ds.WriteObject(ms, cfgIn);
        fileContent = Encoding.UTF8.GetString(ms.ToArray());
        Console.WriteLine (fileContent);
   }
   // yields: <collection xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><item>item1</item><item>item2</item><item>item3</item></collection>

   ConfigWrapper cfgOut = null;
   using (var sr = new StringReader(fileContent))
   {
        using(var xr = XmlReader.Create(sr))
        {
            cfgOut = ds.ReadObject(xr) as ConfigWrapper;
            // cfgOut.Dump(); //view in LinqPad
            if(cfgOut != null)
                // yields 'item2'
                Console.WriteLine (cfgOut[1]);
        }
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜