1

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?

3
  • 2
    That's not valid XML... the first Table doesn't have an endtag called Table... Commented Jun 10, 2013 at 11:17
  • I really prefer to use XmlSerializer over XElement or XmlDocument. Commented Jun 10, 2013 at 11:17
  • @Fendy XDocument > XmlSerializer > XmlDocument Commented Jun 10, 2013 at 11:19

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good point on casting attribute instead of accessing Value property
2

You can use XPath (extension is in System.Xml.XPath namespace) to select all items in one line:

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

Comments

1

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;

Comments

1

using xml document
XmlDocument xdoc = new XmlDocument();

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.