简体   繁体   中英

XmlDocument SelectSingleNode

On Stack Overflow there is a document explaining the use of XmlDocument and how to select a node.

C# XmlDocument SelectSingleNode without attribute

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".

<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. It returned null when I searched for CharacterObject as well. No matter what XML node I search for the function SelectSingleNode returns null. This means I must be using SingleSelectNode incorrectly just not sure how.

I would like SelectSingleNode to return the node so that InnerText will return the Version information in the XML Node. 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. So in your case it is CharacterObject already. When you call .SelectSingleNode('/CharacterObject') for it - you are requesting an CharacterObject element inside the root CharacterObject - which is not there at all.

You can simply use XmlDocument.DocumentElement.InnerText to achieve the result you want.

This particular problem has a solution. This might be due to the namespace attribute in the XML root node itself. Eliminating this attribute solves my issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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