且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用LINQ获得通过名字元素XML

更新时间:2023-11-07 13:56:52

假设元素< A:进入> 元素:

  VAR IDS = element.Element(项目)
.Elements(项目)
。选择(项目=方式> item.Element(ID)值) ;



元素元素方法返回唯一的直接孩子,不是所有的后裔,所以它不会返回&LT;项目&GT; 元素,它在<数据&GT;


I've chosen the title here as my problem is I need to get the Item nodes mentioned in the example. I have the following XML and am having problems using LINQ to query it, I've been able to parse XML before - however I've been stuck on this for hours and hope someone can help. Here is my XML data below (example data):

<a:entry xmlns:a="http://www.w3.org/2005/Atom">
<a:id>98765</a:id>
<info>Data Catalogue</info>
    <data>
    <items>
          <item>
                <id>123456</id>
                <value>Item One</value>
          </item>
          <item>
                <id>654321</id>
                <value>Item Two</value>
          </item>
        <items>
    </data>
    <items>
      <item>
        <id>123456</id>
        <value>Item One</value>
      </item>
      <item>
        <id>654321</id>
        <value>Item Two</value>
      </item>
    <items>
  <a:author>
    <a:name>Catalogue</a:name>
  </a:author>
</a:entry>

I want to be able to extract the ID from the Item XML tag under Items, however there is an Items Tag with Item entries under data I DO NOT want these nodes at all - I want root/items/id/id if this were expressed as path. I've tried everything I know with LINQ so if someone could help, things to note although this is sample data it is based on the system - the format cannot be changed so that is not an acceptable solution.
I can't seem to determine where I'm going wrong - every LINQ expression I try returns nothing, I think the namespace is an issue and have tried to integrate this but I'm going in circles.
Solution must work in Silverlight and C#

I have tried the following:

    IEnumerable<XElement> nodes = 
element.Elements().Where(e => e.Name.LocalName == "items")

However this gets me all the "items" including the ones under "data" I don't want those.


If I do the following on my XML I do see the Names of the Elements displayed:

XElement element = XElement.Parse(data);
foreach (XElement node in element.Elements())
{
  MessageBox.Show(node.Name.LocalName);
}

However when I do this I cannot see the node names under items at all - I've checked the XElement and it does have the node and when I output the names above it "items" shows up along with info and id!

  foreach (XElement node in element.Elements("items"))
  {
    MessageBox.Show(node.Name.LocalName);
  }

Assuming element is your <a:entry> element:

var ids = element.Element("items")
                 .Elements("item")
                 .Select(item => item.Element("id").Value);

The Element and Elements methods return only direct children, not all descendants, so it doesn't return the <items> element which is under <data>