0

我正在使用 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();
}

知道我可能缺少什么吗?任何帮助将不胜感激!

4

1 回答 1

2

CommandCollection应该用属性标记[System.Xml.Serialization.XmlRoot("command_strings")]。您还应该为它添加一个属性version并用属性标记它XmlAttribute

于 2012-08-06T04:31:36.410 回答