【发布时间】:2015-05-26 12:08:58
【问题描述】:
我正在尝试反序列化一个如下所示的 XML 文件:
<xml>
<classes>
<class name="EventLog">
<attribute name="TYPE" type="int"></attribute>
<attribute name="DESCRIPTION" type="string"></attribute>
<attribute name="ISSUEDBY" type="string></attribute>
<attribute name="DATE" type="hr_clock"></attribute>
</class>
<class name="test">
<attribute name="ttt" type="int"></attribute>
<attribute name="ppp" type="string"></attribute>
<attribute name="xxx" type="string"></attribute>
<attribute name="aaa" type="hr_clock"></attribute>
</class>
</classes>
<filters>
<filter name="COILORDERFILTER">
<attribute name="COILID" type="string"></attribute>
<attribute name="RELIABID" type="string"></attribute>
</filter>
<filter name="DriveDataFilter">
<attribute name="DRIVEID" type="string"></attribute>
</filter>
</filters>
</xml>
我只需要节点classes 之间的类。我为反序列化创建了以下类:
[Serializable()]
[System.Xml.Serialization.XmlRoot("classes")]
public class ClassCollection
{
[XmlArray("class")]
[XmlArrayItem("attribute", typeof(SingleClass))]
public SingleClass[] singleClass { get; set; }
}
[Serializable()]
public class SingleClass
{
[System.Xml.Serialization.XmlAttribute("name")]
public string name { get; set; }
[System.Xml.Serialization.XmlAttribute("type")]
public string type { get; set; }
}
class Program
{
static void Main(string[] args)
{
ClassCollection classes = null;
string path = @"C:\Users\test\Desktop\Eventlog.xml";
XmlSerializer serializer = new XmlSerializer(typeof(ClassCollection));
StreamReader reader = new StreamReader(path);
try
{
classes = (ClassCollection)serializer.Deserialize(reader);
}
catch (InvalidOperationException excep)
{
Console.WriteLine(excep.ToString());
}
Console.Read();
}
}
谁能告诉我“怎么了”?
【问题讨论】:
-
代码是否抛出异常
-
“出了什么问题”你必须告诉我们出了什么问题
-
第一次影响,我会说您正在尝试反序列化类节点,但您将完整的 xml 提供给序列化程序
-
请注意,这种序列化不需要
Serializable属性...stackoverflow.com/questions/392431/… -
注意:这里缺少一个结束引号:
<attribute name="ISSUEDBY" type="string></attribute>- 你需要先解决这个问题
标签: c# xml deserialization