Using linq2xml to query a single item deep within
Posted
by BrettRobi
on Stack Overflow
See other posts from Stack Overflow
or by BrettRobi
Published on 2010-06-11T17:17:52Z
Indexed on
2010/06/11
17:22 UTC
Read the original article
Hit count: 222
linq-to-xml
I'm wondering if there is a robust and graceful way using linq2xml to query an item deep within an xml hierarchy. For example:
<?xml version="1.0" encoding="utf-8" ?>
<data>
<core id="01234">
<field1>some data</field1>
<field2>more data</field2>
<metadata>
<response>
<status code="0">Success</status>
<content>
<job>f1b5c3f8-e6b1-4ae4-905a-a7c5de3f13c6</job>
<id>id of the content</id>
</content>
</response>
</metadata>
</core>
</data>
With this xml how do I query the value of without using something like this:
var doc = XElement.Load("file.xml");
string id = (string)doc.Element("core")
.Element("metadata")
.Element("response")
.Element("content")
.Element("id");
I don't like the above approach because it is error prone (throws exception if any tag is missing in the hierarchy) and honestly ugly. Is there a more robust and graceful approach, perhaps using the sql-like syntax of linq?
© Stack Overflow or respective owner