Home > Blockchain >  XmlDocument SelectSingleNode
XmlDocument SelectSingleNode

Time:09-14

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related