我正在尝试开发Windows Phone 8应用程序(我是wp8开发中的新手)。
我有一个如下所示的XML文件:
<?xml version="1.0" ?> <root> <quotes> <quote> <author></author> <text></text> <text></text> <text></text> </quote> </quotes> </root>
这是我的Quotes类:
[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; }
这个工作在每个具有一个<text>
部分的结构中都很好。 但是我有很多<text>
如果我使用上面的C#代码,只有第一个<text>
部分被parsing,其他人被忽略。 我需要为单个XML Feed中的每个<text>
部分创build单独的List或ObservableCollection。
改变你的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。