简体   繁体   English

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

[英]XML Deserialization without a namespace

I'm having a bit of trouble deserializing an XML that doesn't have a namespace. 我在重新序列化没有命名空间的XML时遇到了一些麻烦。 The odd thing is that I'm getting an exception saying "There is an error in XML document (2,2)."; 奇怪的是,我得到一个例外,说“XML文档中存在错误(2,2)。”; Inner Exception "command_strings xmlns = was not expected.". 内部异常“command_strings xmlns =不是预期的。” I'm coding in VS2008. 我在VS2008编码。

My 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="F" cmd_string="1" />
    </commands>
</command_strings>

My class 我的课

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

Try this for your deserialization. 试试这个反序列化。

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

You may also try instead of putting the Root attribute above CommandCollection, use 您也可以尝试而不是将Root属性放在CommandCollection之上,使用

[XmlType("commands_strings")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM