繁体   English   中英

在WP8应用程序中反序列化XML

[英]Deserialize XML in a WP8 Application

我正在尝试开发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>部分,其他部分将被忽略。 我需要在单个XML提要中为每个<text>部分创建单独的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()
};

我已经使用以下QuotesQuote类声明对它进行了测试:

public class Quotes
{
    public List<Quote> Collection { get; set; }
}

public class Quote
{
    public string author { get; set; }

    public string text { get; set; }
}

不再需要属性,因为这种方法不使用XmlSerialization。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM