没有命名空间的XML反序列化

3

我遇到了一些反序列化问题,因为XML没有命名空间。奇怪的是,我收到了一个异常,说“XML文档(2,2)存在错误。”;内部异常“command_strings xmlns = was not expected.”。我在VS2008中编码。

我的XML:

<?xml version="1.0" encoding="utf-8"?>
<command_strings version="1">
    <commands>
         <command cmd_id="1" state_id="1" label="On" cmd_type="F" cmd_string="1" />
    </commands>
</command_strings>

我的班级

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; }
}

[System.Xml.Serialization.XmlRoot("commands_strings")]
public class CommandCollection
{
    [System.Xml.Serialization.XmlAttribute("version")]
    public int version { get; set; }

    [XmlArray("commands")]
    [XmlArrayItem("command", typeof(Command))]
    public Command[] Command { get; set; }
}

public bool IsValidXML()
{
    CommandCollection commandscollection = null;
    XmlSerializer dserial = new XmlSerializer(typeof(CommandCollection));

    using (StreamReader streamReader = new StreamReader(@"C:\123.xml"))
    {
        commandscollection = (CommandCollection)dserial.Deserialize(streamReader);
        streamReader.Close();
    }
}
1个回答

2
请尝试对你的反序列化进行以下操作。
Stream Read = null;
object m_Configuration = null;
try
{
     FileInfo FI = new FileInfo("C:\\");

     Read = FI.OpenRead();
     XmlSerializer serializer = new XmlSerializer(typeof(CommandCollection));

     m_Configuration = serializer.Deserialize(Read);

}
finally
{
     if (Read != null)
     {
           Read.Close();
     }
}

您可以尝试将Root属性放在CommandCollection之上,而不是使用。
[XmlType("commands_strings")]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接