1

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!

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Ronald
  • 1,532
  • 4
  • 18
  • 34
  • Thank you for all your answers. Seems to me all of you are right, so I'll just select the first one that answered and +1 to each. – Ronald Nov 29 '11 at 14:41

3 Answers3

2

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;
Paolo Falabella
  • 24,914
  • 3
  • 72
  • 86
  • what is `inxml` here in your answer it is giving me error while writing the query `Error 1 Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable'. 'Where' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'? D:\RND\TinyMce\Default.aspx.cs 148 30 D:\RND\TinyMce\ ` – Murtaza Mar 07 '12 at 13:10
  • it's a string containing your xml – Paolo Falabella Mar 07 '12 at 13:17
  • also, looking at the error you get, seems you should add `using System.Linq; using System.Xml.Linq;` – Paolo Falabella Mar 07 '12 at 15:56
  • I have already added the reference of the above two namespaces. – Murtaza Mar 09 '12 at 04:19
1

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")));
jlew
  • 10,491
  • 1
  • 35
  • 58
1

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
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480