【发布时间】:2009-02-19 16:46:09
【问题描述】:
我有一个XDocument 对象。我想使用 LINQ 在任意深度查询具有特定名称的元素。
当我使用Descendants("element_name") 时,我只得到当前关卡的直接子元素。我正在 XPath 中寻找“//element_name”的等价物...我应该只使用XPath,还是有办法使用 LINQ 方法?
【问题讨论】:
标签: c# .net xml linq linq-to-xml
我有一个XDocument 对象。我想使用 LINQ 在任意深度查询具有特定名称的元素。
当我使用Descendants("element_name") 时,我只得到当前关卡的直接子元素。我正在 XPath 中寻找“//element_name”的等价物...我应该只使用XPath,还是有办法使用 LINQ 方法?
【问题讨论】:
标签: c# .net xml linq linq-to-xml
后代应该工作得很好。这是一个例子:
using System;
using System.Xml.Linq;
class Test
{
static void Main()
{
string xml = @"
<root>
<child id='1'/>
<child id='2'>
<grandchild id='3' />
<grandchild id='4' />
</child>
</root>";
XDocument doc = XDocument.Parse(xml);
foreach (XElement element in doc.Descendants("grandchild"))
{
Console.WriteLine(element);
}
}
}
结果:
<grandchild id="3" /><grandchild id="4" />
【讨论】:
doc.Descendants("Cars").Descendants("Part")(如果他们只是直系子女,我可能会使用.Elements("Part")。
var foo = new XDocument().Descendants("Bar").Descendants("Baz"); 因为Descendants 返回一个空的IEnumerable<XElement> 而不是null。
一个表示命名空间的例子:
String TheDocumentContent =
@"
<TheNamespace:root xmlns:TheNamespace = 'http://www.w3.org/2001/XMLSchema' >
<TheNamespace:GrandParent>
<TheNamespace:Parent>
<TheNamespace:Child theName = 'Fred' />
<TheNamespace:Child theName = 'Gabi' />
<TheNamespace:Child theName = 'George'/>
<TheNamespace:Child theName = 'Grace' />
<TheNamespace:Child theName = 'Sam' />
</TheNamespace:Parent>
</TheNamespace:GrandParent>
</TheNamespace:root>
";
XDocument TheDocument = XDocument.Parse( TheDocumentContent );
//Example 1:
var TheElements1 =
from
AnyElement
in
TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
select
AnyElement;
ResultsTxt.AppendText( TheElements1.Count().ToString() );
//Example 2:
var TheElements2 =
from
AnyElement
in
TheDocument.Descendants( "{http://www.w3.org/2001/XMLSchema}Child" )
where
AnyElement.Attribute( "theName" ).Value.StartsWith( "G" )
select
AnyElement;
foreach ( XElement CurrentElement in TheElements2 )
{
ResultsTxt.AppendText( "\r\n" + CurrentElement.Attribute( "theName" ).Value );
}
【讨论】:
你可以这样做:
xml.Descendants().Where(p => p.Name.LocalName == "Name of the node to find")
其中xml 是XDocument。
请注意,属性 Name 返回一个具有 LocalName 和 Namespace 的对象。这就是为什么如果你想按名称比较,你必须使用Name.LocalName。
【讨论】:
后代将完全满足您的需求,但请确保您已将命名空间名称与元素名称一起包含在内。如果省略它,您可能会得到一个空列表。
【讨论】:
有两种方法可以做到这一点,
以下是使用这些方法的示例,
List<XElement> result = doc.Root.Element("emails").Elements("emailAddress").ToList();
如果使用 XPath,则需要对 IEnumerable 进行一些操作:
IEnumerable<XElement> mails = ((IEnumerable)doc.XPathEvaluate("/emails/emailAddress")).Cast<XElement>();
注意
var res = doc.XPathEvaluate("/emails/emailAddress");
结果要么是空指针,要么没有结果。
【讨论】:
XPathEvaluate 在System.Xml.XPath 命名空间中。
我正在使用XPathSelectElements 扩展方法,其工作方式与XmlDocument.SelectNodes 方法相同:
using System;
using System.Xml.Linq;
using System.Xml.XPath; // for XPathSelectElements
namespace testconsoleApp
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Parse(
@"<root>
<child>
<name>john</name>
</child>
<child>
<name>fred</name>
</child>
<child>
<name>mark</name>
</child>
</root>");
foreach (var childElem in xdoc.XPathSelectElements("//child"))
{
string childName = childElem.Element("name").Value;
Console.WriteLine(childName);
}
}
}
}
【讨论】:
按照@Francisco Goldenstein 的回答,我写了一个扩展方法
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Mediatel.Framework
{
public static class XDocumentHelper
{
public static IEnumerable<XElement> DescendantElements(this XDocument xDocument, string nodeName)
{
return xDocument.Descendants().Where(p => p.Name.LocalName == nodeName);
}
}
}
【讨论】:
这是我基于 LINQ 和 XDocument 类的 Descendants 方法的解决方案的变体
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
XDocument xml = XDocument.Parse(@"
<root>
<child id='1'/>
<child id='2'>
<subChild id='3'>
<extChild id='5' />
<extChild id='6' />
</subChild>
<subChild id='4'>
<extChild id='7' />
</subChild>
</child>
</root>");
xml.Descendants().Where(p => p.Name.LocalName == "extChild")
.ToList()
.ForEach(e => Console.WriteLine(e));
Console.ReadLine();
}
}
【讨论】:
我们知道以上是真的。乔恩永远不会错;现实生活中的愿望可以走得更远。
<ota:OTA_AirAvailRQ
xmlns:ota="http://www.opentravel.org/OTA/2003/05" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">
<ota:OriginDestinationInformation>
<ota:DepartureDateTime>2012-07-20T00:00:00Z</ota:DepartureDateTime>
</ota:OriginDestinationInformation>
</ota:OTA_AirAvailRQ>
例如,通常的问题是,我们如何才能在上面的 XML 文档中获取 EchoToken?或者如何用name属性模糊元素。
您可以通过使用命名空间和如下名称访问它们来找到它们
doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
您可以通过属性内容值找到它,like this one。
【讨论】:
(代码和说明适用于 C#,其他语言可能需要稍作改动)
如果你想从一个有很多子节点的父节点读取数据,这个例子就完美了,例如看看下面的 XML;
<?xml version="1.0" encoding="UTF-8"?>
<emails>
<emailAddress>jdoe@set.ca</emailAddress>
<emailAddress>jsmith@hit.ca</emailAddress>
<emailAddress>rgreen@set_ig.ca</emailAddress>
</emails>
现在使用下面的代码(请记住,XML 文件存储在资源中(有关资源的帮助,请参阅 sn-p 末尾的链接)您可以获取“电子邮件”标签中的每个电子邮件地址。
XDocument doc = XDocument.Parse(Properties.Resources.EmailAddresses);
var emailAddresses = (from emails in doc.Descendants("emailAddress")
select emails.Value);
foreach (var email in emailAddresses)
{
//Comment out if using WPF or Windows Form project
Console.WriteLine(email.ToString());
//Remove comment if using WPF or Windows Form project
//MessageBox.Show(email.ToString());
}
注意:对于控制台应用程序和 WPF 或 Windows 窗体,您必须添加“使用 System.Xml.Linq;” Using 指令位于项目的顶部,对于 Console,您还需要在添加 Using 指令之前添加对此命名空间的引用。同样对于控制台,“属性文件夹”下默认没有资源文件,因此您必须手动添加资源文件。下面的 MSDN 文章,详细解释了这一点。
【讨论】: