在WP8应用程序中反序列化XML [英] Deserialize XML in a WP8 Application
问题描述
我正在尝试开发Windows Phone 8应用程序(我是wp8开发人员中的新手).
I'm trying to develop a Windows phone 8 app (I'm new in wp8 dev).
我有一个看起来像这样的XML文件:
I have an XML file that look like this:
<?xml version="1.0" ?>
<root>
<quotes>
<quote>
<author></author>
<text></text>
<text></text>
<text></text>
</quote>
</quotes>
</root>
这是我的Quotes类:
This is my Quotes class:
[XmlRoot("root")]
public class Quotes
{
[XmlArray("quotes")]
[XmlArrayItem("quote")]
public ObservableCollection<Quote> Collection { get; set; }
}
这是报价类:
This is the quote class:
public class Quote
{
[XmlElement("author")]
public string author { get; set; }
[XmlElement("text")]
public string text { get; set; }
}
然后我使用以下代码对其进行反序列化:
Then I use this code to deserialize it:
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>
This work fine in every feed having this structure with one <text>
section. But I have feed with a lot of <text>
如果我在上面使用C#代码,则仅解析第一个< text>
部分,其他部分将被忽略.我需要为单个XML提要中的每个< text>
部分创建单独的List或ObservableCollection.
If I use C# code above, only first <text>
section is parsed, others are ignored. I need to create separate List or ObservableCollection for each <text>
section in single XML feed.
推荐答案
更改您的 Quote
类以包含 List< string>文字
而不是字符串文字
:
Change your Quote
class to contain List<string> text
instead of string text
:
public class Quote
{
[XmlElement("author")]
public string author { get; set; }
[XmlElement("text")]
public List<string> text { get; set; }
}
更新
Update
由于您应用程序中的现有功能和当前的 Quotes
类实例中:>
Because of existing functionality within your app and current Quote
class members I would leave serialization and use LINQ to XML to load data from XML into Quotes
class instance:
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
类声明对其进行了测试:
I've tested it with following Quotes
and Quote
class declarations:
public class Quotes
{
public List<Quote> Collection { get; set; }
}
public class Quote
{
public string author { get; set; }
public string text { get; set; }
}
不再需要属性,因为这种方法不使用XmlSerialization.
Attributes are no longer necessary because this approach does not use XmlSerialization.
这篇关于在WP8应用程序中反序列化XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!