How to find the root name of a node in a given xml file

Im using a C # .net form application. I have an xml file whose name is hello.xml and it looks like this

<?xml version="1.0" encoding="utf-8" ?> <languages> <language> <key>abc</key> <value>hello how ru</value> </language> <language> <key>def</key> <value>im fine</value> </language> <language> <key>ghi</key> <value>how abt u</value> </language> </languages> 

How can I get root node ie <languages> in a text box. At this time, I will have the xml file name. I am "hello.xml" . Using this, I have to get the root node.

+6
c #
source share
2 answers

Using LINQ to XML, you can do this:

 XDocument doc = XDocument.Load("input.xml"); string rootLocalName = doc.Root.Name.LocalName; textBox1.Text = '<' + rootLocalName + '>'; 

With an XmlDocument, you can use this:

 XmlDocument doc = new XmlDocument(); doc.Load("input.xml"); string rootName = doc.SelectSingleNode("/*").Name; 
+13
source share

Or use the XmlDocument DocumentElement property, as shown here :

 XmlDocument doc = new XmlDocument(); doc.Load("hello.xml"); string root = doc.DocumentElement.Name; textBox1.Text = "<" + root + ">"; 
0
source share

All Articles