我正在尝试解析对象中的xml文件
这是我的名为Changelog.xml
的xml文件<?xml version="1.0" encoding="utf-8" ?>
<Changelog>
<Releases>
<Release>
<Version>1507</Version>
<Date>22-11-2013</Date>
<Changes>
<Change>Change1</Change>
<Change>Change2</Change>
<Change>Change3</Change>
<Change>Change4</Change>
</Changes>
</Release>
<Release>
<Version>1506</Version>
<Date>20-11-2013</Date>
<Changes>
<Change>Change1</Change>
</Changes>
</Release>
</Releases>
</Changelog>
这是我想要将xml转换为
的Changelog对象[XmlRoot()]
public class Changelog
{
private List<Release> releases;
public List<Release> Releases
{
get { return releases; }
set { releases = value; }
}
}
public class Release
{
private string version;
private string date;
private List<ChangeItem> changes;
[XmlElement]
public string Version
{
get { return version; }
set { version = value; }
}
[XmlElement]
public string Date
{
get { return date; }
set { date = value; }
}
[XmlElement]
public List<ChangeItem> Changes
{
get { return changes; }
set { changes = value; }
}
}
public class ChangeItem
{
private string change;
[XmlElement]
public string Change
{
get { return change; }
set { change = value; }
}
}
我在这里阅读文件
XmlSerializer serializer = new XmlSerializer(typeof(Changelog));
Changelog changelog = (Changelog)serializer.Deserialize(new StreamReader(@"changelog.xml"));
Releases = changelog.Releases;
foreach (Release release in Releases)
{
string version = release.Version;
string date = release.Date;
List<ChangeItem> changes = release.Changes; // Has only 1 item
}
问题是更改列表中只有一个对象,尽管我期望1507版本中有4个。
我做错了什么?
答案 0 :(得分:3)
您有使用XmlElement
属性修饰的ChangeItem.Change属性。这意味着它成为另一个元素。
因此xml需要看起来不同。
要使其正常工作,请使用[XmlText]
属性标记该属性。
此外,您的Release.Changes
需要使用XmlArray
和XmlArrayItem
属性进行修饰。
[XmlRoot]
public class Changelog
{
private List releases;
public List Releases
{
get { return releases; }
set { releases = value; }
}
}
public class Release
{
private string version;
private string date;
private List changes;
[XmlElement]
public string Version
{
get { return version; }
set { version = value; }
}
[XmlElement]
public string Date
{
get { return date; }
set { date = value; }
}
[XmlArray("Changes")]
[XmlArrayItem("Change")]
public List Changes
{
get { return changes; }
set { changes = value; }
}
}
public class ChangeItem
{
private string change;
[XmlText]
public string Change
{
get { return change; }
set { change = value; }
}
}
我用粗体标记了我的更改。
答案 1 :(得分:0)
变化
[XmlElement]
public List<ChangeItem> Changes
{
get { return changes; }
set { changes = value; }
}
到
[XmlArray("Changes")]
public List<ChangeItem> Changes
{
get { return changes; }
set { changes = value; }
}