将xml解析为object

时间:2013-11-26 16:16:08

标签: c# xml

我正在尝试将我的xml文件转换为对象列表。

private void ReadChangelog()
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Changelog));
        Changelog changelog = (Changelog)serializer.Deserialize(new StringReader("changelog.xml"));

        foreach (Release release in changelog.Releases)
        {
            string version = release.Version;
            string date = release.Date;
            string changes = release.Changes;
        }
    }

这是我的更改日志类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

[XmlRoot()]
public class Changelog
{
    private Release[] releases;

    public Release[] Releases
    {
        get { return releases; }
        set { releases = value; }
    }
}

public class Release
{
    private string version;
    private string date;
    private string changes;

    [XmlAttribute]
    public string Version
    {
        get { return version; }
        set { version = value; }
    }

    [XmlAttribute]
    public string Date
    {
        get { return date; }
        set { date = value; }
    }

    [XmlAttribute]
    public string Changes
    {
        get { return changes; }
        set { changes = value; }
    }
}  

这是我的xml

<?xml version="1.0" encoding="utf-8" ?>
<Changelog>
  <Releases>
    <Release>
      <Version>1511</Version>
      <Date>25-11-2013</Date>
      <Changes>
        qzdqzdqzdqzdzdzzqefrsrgsrg
      </Changes>
    </Release>
    <Release>
      <Version>1510</Version>
      <Date>25-11-2013</Date>
      <Changes>
        Blabqzdzqdqzdqzd
      </Changes>
    </Release>
    <Release>
  </Releases>
</Changelog>

但是当我尝试运行时,我收到错误

  

InvalidOperationException,xml文档(1,1)包含错误。

我做错了什么?

2 个答案:

答案 0 :(得分:4)

new StringReader("changelog.xml")未读取changelog.xml的内容。相反,此代码会让您尝试反序列化文字“changelog.xml”字符串。我想你想要new StreamReader("changelog.xml")

答案 1 :(得分:1)

StringReader从字符串内容创建stream,而不是从具有给定路径的文件创建。用户StreamReader代替。

Changelog changelog = (Changelog)serializer.Deserialize(new StreamReader("changelog.xml"));

尽管如此,您的代码中还有更多错误:

  1. 您的文档使用元素,而您的类声明使用XmlAttributeAttribute。它不会一起工作。
  2. 您的文档不是正确的XML文档。它有一些未关闭的元素。