Ronald
Ronald

Reputation: 1542

How to filter XML elements using LINQ query for one attribute/field containing a particular substring?

Example:

<Item name="item1">
    <mode = "ax, bx" />
</Item>
<Item name="item2">
    <mode = "bx, cx" />
</Item>
<Item name="item3">
    <mode = "cx, dx" />
</Item>

In the example above I would like to extract all the items with modes containing "cx".

Thanks in advance!

Upvotes: 1

Views: 2934

Answers (3)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102428

Assuming a well formed XML doc:

<Items>
  <Item name="item1">
    <mode>ax, bx</mode>
  </Item>
  <Item name="item2">
    <mode>bx, cx</mode>
  </Item>
  <Item name="item3">
    <mode>cx, dx</mode> 
  </Item>
</Items>

Do something like this:

XElement items = XElement.Load(@"C:\items.xml");

var filteredItems = from item in items.Descendants("Item")
            where item.Element("mode").Value.Contains("cx")
            select item;

foreach (var item in filteredItems)
{
    Console.WriteLine(item.FirstAttribute.Value);
}

Output:

item2
item3

Upvotes: 1

Paolo Falabella
Paolo Falabella

Reputation: 25844

Your XML in the example is not well formed. Assuming you meant:

<Items>
  <Item name="item1">
    <mode>ax, bx</mode>
  </Item>
  <Item name="item2">
    <mode>bx, cx</mode>
  </Item>
  <Item name="item3">
    <mode>cx, dx</mode> 
  </Item>
</Items>

you can do:

var els=from el in XDocument.Parse(inxml).Descendants("Item")
where el.Element("mode").Value.Contains("bx")
select el;

Upvotes: 2

jlew
jlew

Reputation: 10591

That is not legal XML (mode is an element name, you can set it equal to a string), but you should be able to do something like this, assuming that the string you are matching is the element value:

doc.Descendants("Item").Where( item => item.Elements("mode").Any( mode => mode.Value.Contains("cx")));

Upvotes: 1

Related Questions