LINQ to XML查询中的基本过滤 [英] Basic filtering in LINQ to XML Queries
本文介绍了LINQ to XML查询中的基本过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是XDocument和LINQ的新手.这是我正在尝试做的事情:
I am new to XDocument and LINQ. Here is what I am trying to do :
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查询编写为:
Now I need to read all the records with a specific chapter-no. I am writing my LINQ query as :
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没有填充,并且什么也不显示.
but elem_list is not getting populated and nothing is displayed.
推荐答案
.Elements("Chapter")
仅在当前元素的直接子代(xdoc
的根)内搜索.
.Elements("Chapter")
search only within direct children of current element (root for xdoc
).
您可以使用.Descendants("Chapter")
:
IEnumerable<XElement> elem_list = from e in xdoc.Descendants("Chapter")
where (string) e.Attribute("chapter-no") == "1"
select e;
或指定完整的项目路径:
Or specify full item path:
IEnumerable<XElement> elem_list = from e in xdoc.Root.Element("chapters").Elements("Chapter")
where (string) e.Attribute("chapter-no") == "1"
select e;
另一种方法-使用XPath
选择器:
Another approach - with XPath
selector:
xdoc.XPathSelectElements("root/chapters/Chapter[@chapter-no=1]");
using System.Xml.XPath;
是使最后一个示例工作所必需的.
using System.Xml.XPath;
is necessary to make the last sample work.
这篇关于LINQ to XML查询中的基本过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文