Linq to XML,提取属性和元素 [英] Linq to XML, extracting attributes and elements

查看:100
本文介绍了Linq to XML,提取属性和元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是XML的新手,而Linq是XML的新手,我只是找不到很好的指南来解释如何使用它.我有一个结构如下的简单XML字符串

I am new to XML and Linq to XML and I just can't find a good guide that explains how to work with it. I have a simple XML string structured as follows

<mainitem>

  <items>
    <itemdescription>ABC</itemdescription>
    <item>
      <itemtext>XXX</itemtext>
    </item>
    <item>
      <itemtext>YYY</itemtext>
    </item>
    <item>
      <itemtext>ZZZ</itemtext>
    </item>
  </items>

  <overalldescription>ABCDEFG</overalldescription>
  <itemnodes>
    <node caption="XXX" image="XXX"></node>
    <node caption="YYY" image="YYY"></node>
    <node caption="ZZZ" image="ZZZ"></node>
  </itemnodes>
</mainitem>

我正在使用类似C#的代码

I am using C# code like

 var Items = (from xElem in XMLCODEABOVE.Descendants("item")
              select new ItemObject
              {
                  ItemObjectStringProperty = xElem.Element("itemtext").Value,
              }
              );

提取要与我的代码一起使用的itemtext对象的列表.我需要帮助的地方是提取节点元素的标题和图像属性的列表.我还需要总体描述和项目描述.我已经尝试了上述代码的所有变体,都用Descendant替换Elements,将Element替换为Attribute等.我知道这可能是一个基本问题,但是似乎没有直接的指南可以向初学者解释.

to extract a list of the itemtext objects for use with my code. Where I need help is in extracting a list of the caption and image attributes of my node elements. I also need the overalldescription and the itemdescription. I have tried every variation of the above code substituting Descendant for Elements, Element for Attribute etc. I know this is probably a basic question but there doesn't seem to be a straight forward guide out there to explain this to a beginner.

推荐答案

获取字幕

// IEnumerable<string>
var captions = from node in doc.Descendants("node")
               select node.Attribute("caption").Value;

或者一次添加字幕和图像属性:

Or both the captions and image attributes in one shot:

// IEnumerable of the anonymous type
var captions = from node in doc.Descendants("node")
               select new { 
                   caption = node.Attribute("caption").Value,
                   image = node.Attribute("image").Value
               };

有关说明:

 // null ref risk if element doesn't exist
 var itemDesc = doc.Descendants("itemdescription").FirstOrDefault().Value;
 var overallDesc = doc.Descendants("overalldescription ").FirstOrDefault().Value;

这篇关于Linq to XML,提取属性和元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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