C# 如何获取xml文件的所有节点?
假设我有一个XML文件:C# 如何获取xml文件的所有节点?,c#,xml,parsing,nodes,C#,Xml,Parsing,Nodes,假设我有一个XML文件: <Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>Whi
<Names>
<Name>
<FirstName>John</FirstName>
<LastName>Smith</LastName>
</Name>
<Name>
<FirstName>James</FirstName>
<LastName>White</LastName>
</Name>
</Names>
我设法在XmlNodeList中获得了全部,但我不知道SelectNodes是如何工作的
XmlNodeList xnList = xml.SelectNodes(/*What goes here*/);
我想选择所有节点,然后执行xnList的foreach(使用我假设的.Value属性)
这是正确的方法吗?如何使用selectNodes选择所有节点?确保范围内有LINQ和LINQ to XML:
using System.Linq;
using System.Xml.Linq;
如果将它们加载到XDocument
:
var doc = XDocument.Parse(xml); // if from string
var doc = XDocument.Load(xmlFile); // if from file
您可以执行以下操作:
doc.Descendants().Select(n => n.Name).Distinct()
这将为您提供文档中所有不同的XName
s元素的集合。如果您不关心XML名称空间,可以将其更改为:
doc.Descendants().Select(n => n.Name.LocalName).Distinct()
这将为您提供一个字符串形式的所有不同元素名称的集合。有几种方法 使用XDocument和LINQ-XML
foreach(var name in doc.Root.DescendantNodes().OfType<XElement>().Select(x => x.Name).Distinct())
{
Console.WriteLine(name);
}
加
那你就可以了
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)));
很抱歉,'System.Xml.XmlDocument'不包含'degenerats'的定义,我应该导入我没有的东西吗?正如我所说,要做到这一点,您需要
XDocument
,而不是XmlDocument
。我认为XDocument
更容易使用,因此我建议您使用它而不是XmlDocument
。哦,对不起,但是我得到了与XDocument相同的错误消息:错误1'System.Xml.Linq.XDocument'不包含'degenerats'的定义,并且找不到接受'System.Xml.Linq.XDocument'类型的第一个参数的扩展方法'degenerats'(是否缺少using指令或程序集引用?)C:\Users\majo\Desktop\obligatio\ConsoleApplication1\Program.cs 66 17 exerciseOne有一个小的拼写错误(子体
拼写为子体
)。现在已修复,请再试一次。@yamen ahh捕捉得很好,但现在它给了我:错误1“System.Collections.Generic.IEnumerable”不包含“Select”的定义,并且找不到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的扩展方法“Select”(是否缺少using指令或程序集引用?)C:\Users\majo\Desktop\obligatio\ConsoleApplication1\Program.cs 66 31 ExerciseOne有什么想法为什么?为什么这么详细doc.Root.degenantNodes().OfType()
与doc.degenders()
相同(除了后者可能更有效)。我不知道你为什么要提出两种不同的方法,XElement
在.Net 3.5之前是不可用的。我不确定还应该导入什么:'Error 1'System.Collections.Generic.IEnumerable'不包含'OfType'的定义,并且找不到'OfType'的扩展方法'OfType'接受'System.Collections.Generic.IEnumerable'类型的第一个参数(是否缺少using指令或程序集引用?)C:\Users\majo\Desktop\OblicationIO\ConsoleApplication1\Program.cs 66 61 ExerciseOne`
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();
using System.Xml.Linq;
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)));