4

使用 Linq to XML 和下面的示例 XML 文档,我如何获得“itemColor”为蓝色的“itemType”的值?

<?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>
4

2 回答 2

2
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"

另一种选择是使用 XPath 的单行:

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

顺便说一句,对于使用 XDocument 的 XPath 扩展,您应该使用System.Xml.XPath命名空间。

于 2013-03-19T06:52:21.050 回答
0

这应该可以解决问题:

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;

顺便说一句:这不是LINQ to SQL(在这个例子中 SQL 来自哪里),而是LINQ to XML

于 2013-03-19T06:48:22.440 回答