如何使用 XMLDocument 类从 C# 中的 XML 文件中获取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17383387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get data from an XML File in C# using XMLDocument class?
提问by Tom McClean
Good Evening All, and happy weekend!.
大家晚上好,周末快乐!。
I have been trying all day to understand how to parse my simple XML file so I can understand it enough to write a personal project I want to work on.
我一整天都在尝试了解如何解析我的简单 XML 文件,以便我能够充分理解它来编写我想要从事的个人项目。
I have been reading articles on this site and others but cannot get past where I am :(
我一直在阅读本网站和其他网站上的文章,但无法超越我所在的位置:(
My XML Document is ...
我的 XML 文档是...
<XML>
<User>
<ID>123456789</ID>
<Device>My PC</Device>
</User>
<History>
<CreationTime>27 June 2013</CreationTime>
<UpdatedTime>29 June 2013</UpdatedTime>
<LastUsage>30 June 2013</LastUsage>
<UsageCount>103</UsageCount>
</History>
<Configuration>
<Name>Test Item</Name>
<Details>READ ME</Details>
<Enabled>true</Enabled>
</Configuration>
</XML>
I am trying to get the value in the details element (READ ME). Below is my code
我正在尝试获取详细信息元素中的值(自述)。下面是我的代码
// Start Logging Progress
Console.WriteLine("Test Application - XML Parsing and Creating");
Console.ReadKey();
// Load XML Document
XmlDocument MyDoc = new XmlDocument(); MyDoc.Load(@"E:\MyXML.XML");
// Select Node
XmlNode MyNode = MyDoc.SelectSingleNode("XML/Configuration/Details");
// Output Node Value
Console.WriteLine(String.Concat("Details: ", MyNode.Value));
// Pause
Console.ReadKey();
My console application is running and outputing "Target: " but not giving me the detail within the element.
我的控制台应用程序正在运行并输出“目标:”,但没有提供元素中的详细信息。
Can somebody see why this is happening, and perhaps give me advice if I am completely off the wheel? I have no previous knowledge in reading XML files; hence where I am now :)
有人能明白为什么会这样吗,如果我完全不在状态,也许会给我建议?我以前没有阅读 XML 文件的知识;因此我现在在哪里:)
Thanks! Tom
谢谢!汤姆
采纳答案by nemesv
With the your XPATH expression
使用您的 XPATH 表达式
// Select Node
XmlNode MyNode = MyDoc.SelectSingleNode("XML/Configuration/Details");
your are selection an element so the type of the MyNode will be XmlElementbut the Valueof an XmlElementis always null(see on MSDN) so you need to use XmlElement.InnerTextor XmlElement.InnerXmlisntead.
您选择了一个元素,因此 MyNode 的类型将是,XmlElement但Valuean 的XmlElement类型始终是null(参见MSDN),因此您需要使用XmlElement.InnerText或 XmlElement.InnerXmlistad。
So the changed your code to
所以将您的代码更改为
// Output Node Value
Console.WriteLine(String.Concat("Details: ", MyNode.InnerText));
Or you can select the content of an element with using the XPATH text()function, in this case MyNode will be XmlTextwhere you get its value with Value:
或者您可以使用 XPATHtext()函数选择元素的内容,在这种情况下,MyNode 将是XmlText您获得其值的地方Value:
// Select Node
XmlNode MyNode = MyDoc.SelectSingleNode("XML/Configuration/Details/text()");
// Output Node Value
Console.WriteLine(String.Concat("Details: ", MyNode.Value));
As a sidenote if you are anyway learning XML manipulation in C# you should check out LINQ to XMLwhich is another/newer way to working with XML in C#.
作为旁注,如果您无论如何都在 C# 中学习 XML 操作,您应该查看LINQ to XML,这是在 C# 中使用 XML 的另一种/更新的方法。
回答by Jason Williams
Just for interest, a little-known "simple" syntax is this:
出于兴趣,一个鲜为人知的“简单”语法是这样的:
XmlDocument myDoc = new XmlDocument();
myDoc.Load(@"D:\MyXML.XML");
string details = myDoc["XML"]["Configuration"]["Details"].InnerText;
Note that this (and the XPath approach) could go pop if your XML doesn't conform to the structure you're expecting, so you'd ideally put some validation in there as well.
请注意,如果您的 XML 不符合您期望的结构,则此(以及 XPath 方法)可能会变得流行,因此您最好在其中进行一些验证。
回答by m4c_4rthur
U can use Xpath library for that (u must include "System.Xml.XPath"):
您可以为此使用 Xpath 库(您必须包含“System.Xml.XPath”):
XmlDocument document = new XmlDocument();
document.Load("MyXml.xml");
XPathNavigator navigator = document.CreateNavigator();
foreach (XPathNavigator nav in navigator.Select("//Details"))
{
Console.WriteLine(nav.Value);
}
the above code iterate over every node called (Details) extracting information and print it.
上面的代码遍历每个名为 (Details) 的节点,提取信息并打印出来。

