简体   繁体   English

C#XML内联数组反序列化

[英]C# xml inline array deserialization

What is the easiest way to deserialize xml like this: 像这样反序列化xml的最简单方法是什么:

<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 只需将属性定义为数组,但使用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! 使用XDocument!

The best way would be to parse the xml. 最好的方法是解析xml。

Deserializing it would require a scheme that is supported by XmlSerializer, use XDocument to parse it. 反序列化它需要XmlSerializer支持的方案,使用XDocument对其进行解析。

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. 如您所见,它使用特殊的xml模式,这使得xml无法解析,这意味着您将不得不使用XDocument或XmlDocument手动解析xml,或者首先使用XmlSerializer序列化数据,然后反序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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