Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using linq2xml to query a single item deep within

Tags:

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?

like image 519
BrettRobi Avatar asked Dec 04 '25 19:12

BrettRobi


2 Answers

        XDocument doc = XDocument.Load("file.xml");
        var xx = doc.Descendants("id").First().Value;
like image 68
Wondering Avatar answered Dec 06 '25 11:12

Wondering


This will give you an IEnumerable with all the content/id elements. If you need one specific one, you will need to add the conditions

var ids = from content in doc.Descendants("content")
          select content.Element( "id" ).Value;
like image 20
µBio Avatar answered Dec 06 '25 12:12

µBio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!