XML不要反序列化

时间:2018-02-07 16:55:09

标签: c# xml serialization

我正在尝试反序列化XML文件。我写了一个文件的类结构。当我尝试反序列化时,我收到此错误:

  

System.Xml.dll中发生未处理的“System.InvalidOperationException”类型的异常附加信息:XML文档(0,0)中存在错误。

我不知道类结构有什么问题:

这是XML:

<?xml version="1.0" encoding="utf-8" ?>
<Commands>
  <Command Name="ACK" Value="00"></Command>
  <Command Name="Supervise / Poll" Value="01"></Command>
  <Command Name="Sequence number re-sync" Value="02"></Command>
  <Command Name="STATUS" Value="10"></Command>
  <Command Name="REQUEST" Value="20"></Command>
  <Command Name="RESPONSE" Value="30"></Command>
  <Command Name="Validation" Value="33"></Command>
  <Command Name="Stop Request" Value="35"></Command>
  <Command Name="WRITE" Value="40"></Command>
  <Command Name="DATA" Value="50"></Command>
  <Command Name="CONFIG" Value="60"></Command>
  <Command Name="STARTUP" Value="70"></Command>
  <Command Name="Pass-through" Value="80"></Command>
  <Command Name="MULTI COMMAND" Value="90"></Command>
</Commands>

这是类结构:

[XmlRoot("Commands")]
public class XMLCommands
{
    [XmlElement("Command")]
    public List<XMLCommand> Command{ get; set; }

    public XMLCommands()
    {
        Command = new List<XMLCommand>();
    }

    public class XMLCommand
    {

        [XmlAttribute("Name")]
        public string Name { get; set; }

        [XmlAttribute("Value")]
        public string Value { get; set; }

        public XMLCommand()
        {
            Name = "";
            Value = "";
        }
    }
}

以下是我用以下方法阅读XML的方法:

public CoreBusAnalyzing(string PathAnalyze)
    {
        _pathToAnalyze = PathAnalyze;
        _stopAnalyzing = false;
        _XMLModule = new XMLModule();

        //XmlSerializer serializer = new XmlSerializer(typeof(XMLModule));

        //StreamReader reader = new StreamReader("XMLModule.xml");
        //string tmp = reader.ReadToEnd();
        //_XMLModule = (XMLModule)serializer.Deserialize(reader);
        //reader.Close();

        _XMLCommands = new XMLCommands();


        XmlSerializer serializer = new XmlSerializer(typeof(XMLCommands));

        StreamReader reader = new StreamReader("XMLCommand.xml");
        reader.ReadToEnd();
        _XMLCommands = (XMLCommands)serializer.Deserialize(reader);
        reader.Close();
    }

1 个答案:

答案 0 :(得分:3)

您正在将数据流读取到最后,然后将流传递给Deserialize方法 - 此时已经读取了流。

您应该从代码中删除reader.ReadToEnd()行。