有没有一种简单的方法,从 xml 文档中获取所有节点?我需要每个节点、子节点等来检查它们是否具有某些属性。
或者我是否必须爬行文档,询问子节点?
在 LINQ to XML 中,这非常简单:
XDocument doc = XDocument.Load("test.xml"); // Or whatever
var allElements = doc.Descendants();
因此,要查找具有特定属性的所有元素,例如:
var matchingElements = doc.Descendants()
.Where(x => x.Attribute("foo") != null);
假设你想要所有elements。如果你想要全部nodes(包括文本节点等,但是not包括作为单独节点的属性)您将使用DescendantNodes() http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.descendantnodes.aspx反而。
编辑:LINQ to XML 中的命名空间很好。你会使用:
var matchingElements = doc.Descendants()
.Where(x => x.Attribute(XNamespace.Xmlns + "aml") != null);
或者对于不同的命名空间:
XNamespace ns = "http://some.namespace.uri";
var matchingElements = doc.Descendants()
.Where(x => x.Attribute(ns + "foo") != null);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)