简体   繁体   中英

C# xml inline array deserialization

What is the easiest way to deserialize xml like this:

<root>
    <item id="1"/>
    <item id="2"/>
    <item id="3"/>
</root>

Actually, it is possible - the answer here shows how. Just define the property as array but annotate with XmlElement

public class Item
{
    [XmlAttribute("id")]
    public int Id { get ;set; }

    [XmlText]
    public string Name { get; set; }
}

[XmlRoot("root")]
public class Root
{
    [XmlElement("item")]
    public Item[] Items { get;set;}
}
List<string> items = XDocument.Parse("the xml")
                         .Descendants("item")
                         .Select(item => item.Attribute("id").Value).ToList();

Use XDocument!

The best way would be to parse the xml.

Deserializing it would require a scheme that is supported by XmlSerializer, use XDocument to parse it.

Here is an example of serialization:

Define the class

public class item
{
    [XmlAttribute("item")]
    public string id { get; set; }
}

Serialize it

var xs = new XmlSerializer(typeof(item[]));
xs.Serialize(File.Open(@"c:\Users\roman\Desktop\ser.xml", FileMode.OpenOrCreate), new item[] { new item { id = "1" }, new item { id = "1" }, new item { id = "1" } });

Result:

<?xml version="1.0"?>
<ArrayOfItem xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <item item="1" />
  <item item="1" />
  <item item="1" />
</ArrayOfItem>

As you can see it uses a special xml schema, making your xml unparseable, meaning you will either have to parse your xml manually, by using XDocument or XmlDocument, or serialize your data using XmlSerializer first, then deserialize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM