使用内部节点解析xml [英] Parsing xml with inner nodes

查看:134
本文介绍了使用内部节点解析xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析下面给出的xml:

I'm trying to parse the xml given below:

<Item status="SUCCESS" message="">
   <ItemDate>12/21/2012
      <ItemType>MyType1
         <ItemUrl title="ItemTitle">http://www.itemurl1.com</ItemUrl>
      </ItemType>
   </ItemDate>
   <ItemDate>12/22/2012
      <ItemType>MyType2
         <ItemUrl title="Item2Title">http://www.itemurl2.com</ItemUrl>
      </ItemType>
   </ItemDate>
</Item>

如您所见,我不确定我们是否可以调用此xml,但这是我从旧版服务中得到的东西.我需要的是解析它并将其加载到对象图中.我的对象模型如下:

As you could see I'm not sure whether we can call this xml, but this si what I get out of a legacy service. What I'm after is to parse this and load it into an object graph. My object model is as below:

 public class Item
    {
        public string Date { get; set; }
        public string Type { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
    }

因此,基本上,当我完成上述xml/string的解析后,便得到了Item对象的集合.您能建议我如何通过一些代码片段实现这一目标吗?

So, basically when I'm done with parsing the above xml/string I get a collection of Item objects. Can you please suggest me how to achieve this with some code snippet?

我尝试使用XDocument,但是鉴于xml的特殊结构,我无法做到这一点.

I tried with XDocument, but I was not able to do it given the peculiar structure of xml.

谢谢, -迈克

推荐答案

XDocument xdoc = XDocument.Load(path_to_xml);
var query = from date in xdoc.Descendants("ItemDate")
            let type = date.Element("ItemType")
            let url = type.Element("ItemUrl")
            select new Item()
            {
                ItemDate = ((XText)date.FirstNode).Value,
                ItemType = ((XText)type.FirstNode).Value,
                ItemUrl = (string)url,
                ItemTitle = (string)url.Attribute("title"),
            };

这篇关于使用内部节点解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆