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!

1
  • 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. Commented Nov 29, 2011 at 14:41

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

4 Comments

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<System.Xml.Linq.XElement>'. '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\
it's a string containing your xml
also, looking at the error you get, seems you should add using System.Linq; using System.Xml.Linq;
I have already added the reference of the above two namespaces.
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")));

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.