[英]How can I get all the nodes of a xml file?
Let's say I have this XML file: 假设我有这个XML文件:
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
And now I want to print all the names of the node: 现在我要打印节点的所有名称:
Names
Name
FirstName
LastName
I managed to get the all in a XmlNodeList, but I dont know how SelectNodes works. 我设法在XmlNodeList中获取all,但我不知道SelectNodes是如何工作的。
XmlNodeList xnList = xml.SelectNodes(/*What goes here*/);
I want to select all nodes, and then do a foreach of xnList (Using the .Value property I assume). 我想选择所有节点,然后执行xnList的foreach(使用我假设的.Value属性)。
Is this the correct approach? 这是正确的方法吗? How can I use the selectNodes to select all the nodes?
如何使用selectNodes选择所有节点?
Ensuring you have LINQ and LINQ to XML in scope: 确保在范围内具有LINQ和LINQ to XML:
using System.Linq;
using System.Xml.Linq;
If you load them into an XDocument
: 如果将它们加载到
XDocument
:
var doc = XDocument.Parse(xml); // if from string
var doc = XDocument.Load(xmlFile); // if from file
You can do something like: 你可以这样做:
doc.Descendants().Select(n => n.Name).Distinct()
This will give you a collection of all distinct XName
s of elements in the document. 这将为您提供文档中所有不同
XName
元素的集合。 If you don't care about XML namespaces, you can change that to: 如果您不关心XML命名空间,可以将其更改为:
doc.Descendants().Select(n => n.Name.LocalName).Distinct()
which will give you a collection of all distinct element names as strings. 这将为您提供所有不同元素名称的集合作为字符串。
There are several ways of doing it. 有几种方法可以做到这一点。
With XDocument and LINQ-XML 使用XDocument和LINQ-XML
foreach(var name in doc.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct())
{
Console.WriteLine(name);
}
If you are using C# 3.0 or above, you can do this 如果您使用的是C#3.0或更高版本,则可以执行此操作
var data = XElement.Load("c:/test.xml"); // change this to reflect location of your xml file
var allElementNames =
(from e in in data.Descendants()
select e.Name).Distinct();
Add 加
using System.Xml.Linq;
Then you can do 那你可以做
var element = XElement.Parse({Your xml string});
Console.Write(element.Descendants("Name").Select(el => string.Format("{0} {1}", el.Element("FirstName").Value, el.Element("LastName").Value)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.