当我想使用XmlSerializer读取XML文件时,我遇到了问题。 我的xml文件如下:
Window.showModalDialog()
以下是课程:
<?xml version="1.0" encoding="utf-8"?>
<contents>
<section id="1">
<element1>2</element1>
<element2>1</element2>
<idx>1</idx>
<idx>2</idx>
<idx>3</idx>
</section>
<section id="2">
<element1>2</element1>
<element2>1</element2>
</section>
<section id="3"/>
</contents>
反序列化功能:
[Serializable()]
public class section
{
[XmlAttribute("id")]
public string id { get; set; }
[XmlElement("element1")]
public int element1 { get; set; }
[XmlElement("element2")]
public int element2 { get; set; }
[XmlElement("idx")]
public int[] idx { get; set; }
}
[Serializable()]
[XmlRoot("contents")]
public class contents
{
[XmlArray("section")]
[XmlArrayItem("section", typeof(section))]
public section[] section { get; set; }
}
为什么它不起作用? 我参考了https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx,但似乎没用。 请帮帮我!!!!!
答案 0 :(得分:1)
试试这个......
... Usings
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
Classes ...(使用http://xmltocsharp.azurewebsites.net/从您的XML创建)
[XmlRoot(ElementName = "section")]
public class Section
{
[XmlElement(ElementName = "element1")]
public string Element1 { get; set; }
[XmlElement(ElementName = "element2")]
public string Element2 { get; set; }
[XmlElement(ElementName = "idx")]
public List<string> Idx { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "contents")]
public class Contents
{
[XmlElement(ElementName = "section")]
public List<Section> Section { get; set; }
}
...代码
Contents dezerializedXML = new Contents();
// Deserialize to object
XmlSerializer serializer = new XmlSerializer(typeof(Contents));
using (FileStream stream = File.OpenRead(@"xml.xml"))
{
dezerializedXML = (Contents)serializer.Deserialize(stream);
} // Put a break-point here, then mouse-over dezerializedXML
我把你的XML放在一个文件(xml.xml)中并从那里读取....