jimjim
jimjim

Reputation: 2503

C# Linq to XML getting the elements where value of name contains a specific string

I have an XML file that contains following type of elements:

<add name="$(ReferAEP)" value="$(addressA)" />
<add name="$(ReferBEP)" value="$(addressB)" />

what is the linq to xml query to get only elements where "name" attribute contains a value like *EP ? so the above two elements will end up in the result?

Upvotes: 3

Views: 2242

Answers (2)

Guy
Guy

Reputation: 50899

Are you looking for something like

document.Descendants("add").Where(element => element.Attribute("name").Value.EndsWith("EP)"));

Upvotes: 4

Habeeb
Habeeb

Reputation: 8017

If you have an outer element for the xml tags specified in your question like:

<adds>
    <add name="$(ReferAEP)" value="$(addressA)" />
    <add name="$(ReferBEP)" value="$(addressB)" />
</adds>

Then use the below linq query:

var query = from d in xdoc.Descendants("adds").Descendants()
            where d.Attribute("name")?.Value.Contains("EP")
            select d;

Upvotes: 4

Related Questions