user2121236
user2121236

Reputation: 53

Select XML element based on value of sibling

Using Linq to XML and the example XML document below, how would I get the value of "itemType" where the "itemColor" is blue?

<?xml version="1.0" encoding="utf-8" ?>
<items>
    <item>
         <itemName>my item name</itemName>
         <itemType>spoon</itemType>
         <itemColor>red</itemColor>
    </item>
    <item>
         <itemName>your item name</itemName>
         <itemType>fork</itemType>
         <itemColor>blue</itemColor>
    </item>
 </items>

Upvotes: 4

Views: 1207

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

var xdoc = XDocument.Load(path_to_xml);
var itemType = xdoc.Root.Elements("item")
                   .Where(i => (string)i.Element("itemColor") == "blue")
                   .Select(i => (string)i.Element("itemType"))
                   .FirstOrDefault();
// returns "fork"

Another option is single line with XPath:

var type = (string)xdoc.XPathSelectElement("//item[itemColor='blue']/itemType");

BTW for using XPath extensions of XDocument you should use System.Xml.XPath namespace.

Upvotes: 2

bigge
bigge

Reputation: 1496

This should do the trick:

XDocument doc = XDocument.Load("../../sample.xml");
var elements = from item in doc.Descendants("items").Descendants("item")
               where item.Element("itemColor").Value == "blue"
               select item.Element("itemType").Value;

By the way: This is not LINQ to SQL (where would SQL come from in this example) but LINQ to XML

Upvotes: 0

Related Questions