C#:获取 XML 文档的所有节点 [英] C# : Getting all nodes of XML doc
问题描述
有没有一种简单的方法可以从 xml 文档中获取所有节点?我需要每个节点、子节点等来检查它们是否具有某些属性.
Is there a simple way, to get all nodes from an xml document? I need every single node, childnode and so on, to check if they have certain attributes.
或者我是否必须爬过文档,要求子节点?
Or will I have to crawl through the document, asking for childnodes?
推荐答案
在 LINQ to XML 中非常简单:
In LINQ to XML it's extremely easy:
XDocument doc = XDocument.Load("test.xml"); // Or whatever
var allElements = doc.Descendants();
所以要查找具有特定属性的所有元素,例如:
So to find all elements with a particular attribute, for example:
var matchingElements = doc.Descendants()
.Where(x => x.Attribute("foo") != null);
假设您想要所有元素.如果您想要所有节点(包括文本节点等,但不包括作为单独节点的属性),您可以使用DescendantNodes()
.
That's assuming you wanted all elements. If you want all nodes (including text nodes etc, but not including attributes as separate nodes) you'd use DescendantNodes()
instead.
LINQ to XML 中的命名空间很好.你会使用:
Namespaces in LINQ to XML are nice. You'd use:
var matchingElements = doc.Descendants()
.Where(x => x.Attribute(XNamespace.Xmlns + "aml") != null);
或用于不同的命名空间:
or for a different namespace:
XNamespace ns = "http://some.namespace.uri";
var matchingElements = doc.Descendants()
.Where(x => x.Attribute(ns + "foo") != null);
这篇关于C#:获取 XML 文档的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!