我正在使用Visual Studio 2010(c#),我的XML反序列化代码存在一些问题。我无法正确阅读我的XML。
我的XML内容如下:
<?xml version="1.0" encoding="utf-8"?>
<command_strings version="1">
<commands>
<command cmd_id="1" state_id="1" label="On" cmd_type="fixed" cmd_string="1%0D" />
<command cmd_id="1" state_id="3" label="Off" cmd_type="fixed" cmd_string="0%0d" />
</commands>
</command_strings>
我的代码如下:
[Serializable()]
public class Command
{
[System.Xml.Serialization.XmlAttribute("cmd_id")]
public int cmd_id { get; set; }
[System.Xml.Serialization.XmlAttribute("state_id")]
public int state_id { get; set; }
[System.Xml.Serialization.XmlAttribute("label")]
public string label { get; set; }
[System.Xml.Serialization.XmlAttribute("cmd_type")]
public string cmd_type { get; set; }
[System.Xml.Serialization.XmlAttribute("cmd_string")]
public string cmd_string { get; set; }
}
[Serializable()]
[System.Xml.Serialization.XmlRoot("commands")]
public class CommandCollection
{
[XmlArray("commands")]
[XmlArrayItem("command", typeof(Command))]
public Command[] Command { get; set; }
}
public void XMLStrings(string myXML)
{
CommandCollection commandscollection = null;
XmlSerializer dserial = new XmlSerializer(typeof(CommandCollection));
StreamReader streamReader = new StreamReader(@"C:\123.xml");
commandscollection = (CommandCollection)dserial.Deserialize(streamReader);
streamReader.Close();
}
知道我可能缺少什么吗? 任何帮助将不胜感激!
答案 0 :(得分:2)
CommandCollection
类应使用属性[System.Xml.Serialization.XmlRoot("command_strings")]
进行标记。
您还应为version
添加属性,并使用XmlAttribute
属性进行标记。