简体   繁体   English

XmlDocument 选择单节点

[英]XmlDocument SelectSingleNode

On Stack Overflow there is a document explaining the use of XmlDocument and how to select a node.在 Stack Overflow 上有一个文档解释了 XmlDocument 的使用以及如何 select 一个节点。

C# XmlDocument SelectSingleNode without attribute C# XmlDocument SelectSingleNode 无属性

The code presented is the code I am using as follows.提供的代码是我正在使用的代码,如下所示。

XmlDocument doc = new XmlDocument();
doc.Load("C:\\FileXml.xml")
string Version = doc.DocumentElement.SelectSingleNode("/Version").InnerText;
Console.Write(Version); //I want to see 3

The Xml file is shown below "in its entirety". Xml 文件“完整”如下所示。

<CharacterObject xmlns="http://www.w3.org/2005/Atom">
   <Version>3</Version>
   <Path>C:\\FilePath\FileName.xml</Path>
</CharacterObject>

The error that I am receiving is that SelectSingleNode above returns null.我收到的错误是上面的 SelectSingleNode 返回 null。 It returned null when I searched for CharacterObject as well.当我搜索 CharacterObject 时,它也返回了 null。 No matter what XML node I search for the function SelectSingleNode returns null.无论 XML 节点是什么,我搜索 function SelectSingleNode 返回 null。 This means I must be using SingleSelectNode incorrectly just not sure how.这意味着我必须错误地使用 SingleSelectNode 只是不确定如何。

I would like SelectSingleNode to return the node so that InnerText will return the Version information in the XML Node.我希望 SelectSingleNode 返回节点,以便 InnerText 将返回 XML 节点中的版本信息。 I'm just having a problem in usage of reading the information from the nodes.我只是在使用从节点读取信息时遇到问题。

According to documentation on XmlDocument.DocumentElement - it is a root xml element.根据XmlDocument.DocumentElement上的文档- 它是一个根 xml 元素。 So in your case it is CharacterObject already.所以在你的情况下,它已经是CharacterObject了。 When you call .SelectSingleNode('/CharacterObject') for it - you are requesting an CharacterObject element inside the root CharacterObject - which is not there at all.当您为其调用.SelectSingleNode('/CharacterObject')时-您正在请求根CharacterObject内的CharacterObject元素-根本不存在。

You can simply use XmlDocument.DocumentElement.InnerText to achieve the result you want.您可以简单地使用XmlDocument.DocumentElement.InnerText来实现您想要的结果。

This particular problem has a solution.这个特殊的问题有一个解决方案。 This might be due to the namespace attribute in the XML root node itself.这可能是由于 XML 根节点本身的命名空间属性。 Eliminating this attribute solves my issue.消除此属性解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM