Steve
Steve

Reputation: 1694

Simple search of XDocument

Suppose I want to return the value that has the XPath "/Tier1/Tier2/Setting[Name=aUniqueName]/theValue"

I'm using XDocument so I can use linq, but is there short way to get this value with proper error checking? All I can think of is to get each tier, check each tier is not null, then proceed to the next tier and repeat - which seems a lot more effort than using a single line of XPath in XmlDocument.

Upvotes: 1

Views: 64

Answers (2)

Enigmativity
Enigmativity

Reputation: 117057

Here's a LINQ query that will do it for you:

var query =
    from t2 in xd.Root.Elements("Tier2")
    from s in t2.Elements("Setting")
    where s.Attributes("Name").Any(a => a.Value == "aUniqueName")
    select s.Value;

This assumes your document structure looks like this:

<Tier1>
    <Tier2>
        <Setting Name="aUniqueName">theValue</Setting>
    </Tier2>
</Tier1>

Upvotes: 1

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

You can use XPath with XDocument. Use XPathSelectElements method.

Upvotes: 4

Related Questions