简体   繁体   中英

C# XML get nodes based on attribute

I have the following xml:

<root ...>
  <Tables>
    <Table content="..">
    </Table>
    <Table content="interesting">
      <Item ...></Item>
      <Item ...></Item>
      <Item ...></Item>
    </Table>
    ...etc...
  </Tables>
</root>

I'm using the following code to get the items from the 'interesting' node:

XElement xel = XElement.Parse(resp);

var nodes = from n in xel.Elements("Tables").Elements("Table")
            where n.Attribute("content").Value == "interesting"
            select n;

var items = from i in nodes.Elements()
            select i;

Is there a simpler, cleaner way to achieve this?

Well there's no point in using a query expression for items , and you can wrap the whole thing up very easily in a single statement. I wouldn't even bother with a query expression for that:

var items = XElement.Parse(resp)
                    .Elements("Tables")
                    .Elements("Table")
                    .Where(n => n.Attribute("content").Value == "interesting")
                    .Elements();

Note that this (and your current query) will throw an exception for any Table element without a content attribute. If you'd rather just skip it, you can use:

.Where(n => (string) n.Attribute("content") == "interesting")

instead.

您可以使用XPath(扩展名在System.Xml.XPath命名空间中)在一行中选择所有项:

var items = xel.XPathSelectElements("//Table[@content='interesting']/Item");

If you don't need nodes outside of your query for items , you can just do this:

var items = from n in xel.Elements("Tables").Elements("Table")
            where n.Attribute("content").Value == "interesting"
            from i in n.Elements()
            select i;

using xml document
XmlDocument xdoc = new XmlDocument();

var item= xdoc.GetElementsByTagName("Table[@content='interesting']/Item");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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