0

我是 XDocument 和 LINQ 的新手。这是我正在尝试做的事情:

XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <chapters total-chapters="3">
    <Chapter chapter-no="1">
      <chapter-summary>this is chapter 1</chapter-summary>
    </Chapter>
    <Chapter chapter-no="2">
      <chapter-summary>this is chapter 2</chapter-summary>
    </Chapter>
    <Chapter chapter-no="3">
      <chapter-summary>this is chapter 3</chapter-summary>
    </Chapter>
    <Chapter chapter-no="4">
      <chapter-summary>this is chapter 4</chapter-summary>
    </Chapter>
</chapters>
</root>

现在我需要阅读具有特定章节编号的所有记录。我正在编写我的 LINQ 查询:

IEnumerable<XElement> elem_list = 
    from e in xdoc.Elements("Chapter") 
    where (string) e.Attribute("chapter-no") == "1" 
    select e;

foreach (XElement e in elem_list)
{
    Console.WriteLine(e);
}

但是 elem_list 没有被填充,也没有显示任何内容。

4

2 回答 2

2

.Elements("Chapter")仅在当前元素的直接子元素中搜索(根为xdoc)。

您可以使用.Descendants("Chapter")

IEnumerable<XElement> elem_list = from e in xdoc.Descendants("Chapter")
                                  where (string) e.Attribute("chapter-no") == "1"
                                  select e;

或指定完整的项目路径:

IEnumerable<XElement> elem_list = from e in xdoc.Root.Element("chapters").Elements("Chapter")
                                  where (string) e.Attribute("chapter-no") == "1"
                                  select e;

另一种方法 - 使用XPath选择器:

xdoc.XPathSelectElements("root/chapters/Chapter[@chapter-no=1]");

using System.Xml.XPath;是使最后一个样本工作所必需的。

于 2013-03-16T19:01:21.150 回答
0

您可以执行以下操作:

IEnumerable<XElement> elem_list = 
   xdoc.Descendants("Chapter")
   .Where (c => c.Attribute("chapter-no").Value.Equals("1"));
于 2013-03-16T19:08:29.930 回答