C#xml内联数组反序列化
反序列化xml的最简单方法是什么:C#xml内联数组反序列化,c#,xml,C#,Xml,反序列化xml的最简单方法是什么: <root> <item id="1"/> <item id="2"/> <item id="3"/> </root> 最好的方法是解析xml 反序列化它需要XmlSerializer支持的方案,请使用XDocument对其进行解析 以下是序列化的一个示例: 定义类 public class item { [XmlAttribute("item")] publ
<root>
<item id="1"/>
<item id="2"/>
<item id="3"/>
</root>
最好的方法是解析xml 反序列化它需要XmlSerializer支持的方案,请使用XDocument对其进行解析 以下是序列化的一个示例: 定义类
public class item
{
[XmlAttribute("item")]
public string id { get; set; }
}
将其序列化
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" } });
结果:
<?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>
正如您所见,它使用了一种特殊的xml模式,使您的xml不可解析,这意味着您必须使用XDocument或XmlDocument手动解析xml,或者首先使用XmlSerializer序列化数据,然后对其进行反序列化。List items=XDocument.parse(“xml”)
List<string> items = XDocument.Parse("the xml")
.Descendants("item")
.Select(item => item.Attribute("id").Value).ToList();
.后代(“项目”)
.Select(item=>item.Attribute(“id”).Value).ToList();
使用XDocument 事实上,这是可能的-答案说明了如何。只需将属性定义为数组,但使用
xmlement
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;}
}
反序列化为什么形式?