将XML反序列化为两个类

时间:2014-07-14 08:26:39

标签: c# xml-serialization

我有一个XML文件:

<?xml version="1.0" encoding="utf-8" ?>
<Data>
    <SerialNumber>123321</SerialNumber>
    <AFCommand>ALL</AFCommand>
    <SqlServerAdress>./test123</SqlServerAdress>
    <Mode>SE</Mode>
    <Prerequsites>Prerequsites check failed</Prerequsites>
    <Connection>Connection check failed</Connection>
</Data>

我希望将其反序列化为两个类:

    [XmlRoot("Data")]
public class ConsoleMessages
{
    [XmlElement("Prerequsites")]
    public string prerequsitesCheckFailed { get; set; }

    [XmlElement("Connection")]
    public string connectionFailed { get; set; }
}

 [XmlRoot("Data")]
    public class InstallationAdditionalData
    {
        [XmlElement("SerialNumber")]
        public string SerialNumber { get; set; }

        [XmlElement("AFCommand")]
        public string AFCommand { get; set; }

        [XmlElement("SqlServerAdress")]
        public string SqlServerAdress { get; set; }

        [XmlElement("Mode")]
        public string Mode { get; set; }
    }

使用此代码:

 private void DeserializeAdditionalData(string filename)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(InstallationAdditionalData));
        StreamReader fs = new StreamReader(filename);
        XmlReader reader = new XmlTextReader(fs);
        try
        {
            this.InstallationAdditionalData = (InstallationAdditionalData)serializer.Deserialize(reader);
            serializer = new XmlSerializer(typeof(ConsoleMessages));
            var a = (ConsoleMessages)serializer.Deserialize(reader);
        }
        catch (Exception)
        {
            Environment.Exit(11);// błąd w czasie odczytu xml
        }
        finally
        {
            fs.Close();
        }
    }

有了这个效果:

  • 正确反序列化InstallationAdditionalData。
  • ConsoleMessages始终为null

我是否需要回放StreamReader / XMLReader?如果是的话。 Intellisense不会给我任何回报: fs.Position or reader.Position

1 个答案:

答案 0 :(得分:1)

是的,您需要回放流以便能够再次反序列化它。

如果您传递文件名,

StreamReader会在内部使用FileStream。最简单的解决方案是自己创建FileStream,然后传入。

FileStream fs = File.OpenRead(filename);
StreamReader reader = new StreamReader(fs);

//...

fs.Position = 0;
reader.DiscardBufferedData();

//...