我正在尝试开发 Windows Phone 8 应用程序(我是 wp8 开发人员的新手)。
我有一个如下所示的 XML 文件:
<?xml version="1.0" ?>
<root>
<quotes>
<quote>
<author></author>
<text></text>
<text></text>
<text></text>
</quote>
</quotes>
</root>
这是我的报价单类:
[XmlRoot("root")]
public class Quotes
{
[XmlArray("quotes")]
[XmlArrayItem("quote")]
public ObservableCollection<Quote> Collection { get; set; }
}
这是引用类:
public class Quote
{
[XmlElement("author")]
public string author { get; set; }
[XmlElement("text")]
public string text { get; set; }
}
然后我使用这段代码反序列化它:
XmlSerializer serializer = new XmlSerializer(typeof(Quotes));
XDocument document = XDocument.Parse(e.Result);
Quotes quotes = (Quotes) serializer.Deserialize(document.CreateReader());
quotesList.ItemsSource = quotes.Collection;
// selected Quote
Quote quote;
public QuotePage()
{
InitializeComponent();
// get selected quote from App Class
var app = App.Current as App;
quote = app.selectedQuote;
// show quote details in page
author.Text = quote.author;
text.Text = quote.text;
}
这在每个具有这种结构的 feed 中工作正常,一个 <text>
部分。但我有很多 <text>
的饲料
如果我使用上面的 C# 代码,只有第一个 <text>
部分被解析,其他部分被忽略。我需要为每个 <text>
创建单独的列表或 ObservableCollection单个 XML 提要中的部分。
最佳答案
更改您的 Quote
类包含 List<string> text
而不是 string text
:
public class Quote
{
[XmlElement("author")]
public string author { get; set; }
[XmlElement("text")]
public List<string> text { get; set; }
}
更新
由于您应用中的现有功能和当前 Quote
类成员 我将离开序列化并使用 LINQ to XML 将数据从 XML 加载到 Quotes
类实例:
XDocument document = XDocument.Parse(e.Result);
Quotes quotes = new Quotes() {
Collection = document.Root
.Element("quotes")
.Elements("quote")
.Select(q => new {
xml = q,
Author = (string) q.Element("author")
})
.SelectMany(q => q.xml.Elements("text")
.Select(t => new Quote() {
author = q.Author,
text = (string)t
}))
.ToList()
};
我已经使用以下 Quotes
对其进行了测试和 Quote
类声明:
public class Quotes
{
public List<Quote> Collection { get; set; }
}
public class Quote
{
public string author { get; set; }
public string text { get; set; }
}
不再需要属性,因为这种方法不使用 XmlSerialization。
关于c# - 在 WP8 应用程序中反序列化 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480625/