Wednesday, 3 July 2013

Read the Root Element Name from the Xml

Some times , there is a need of finding a root element name from a Xml. This can be done in various ways.

Let we Consider following Xml as Input "Sample.xml"

 First way

            XDocument doc=XDocument.Load("sample.xml");
             string rootelename = doc.Root.Name

 Second way  

            XmlDocument xdoc=new XmlDocument();
            XmlNode firstelement=xdoc.SelectSingleNode("(/*)");
            string rootelename = firstelement.Name;

For the Above two code Output will be  :variable  rootelename  have a value of "Employess"

Let we consider a another Example in this scenario , A xml with Prefix refer to a namespace
<?xml version="1.0"?>
<bk:book xmlns:bk=''
    <bk:title>Cheaper by the Dozen</bk:title>
For this xml above two code will give an output as Variable rootelename have a value of "bk:book"
"bk:book" is not only the root element name , It is the combination of prefix+root element name

now we need to get the root element name separate from prefix by the following way.

 Third way 

             XmlTextReader reader=new XmlTextReader("sample.xml");
                        string rootelename=reader.LocalName;
                        string prefix=reader.Prefix;

Here rootelename variable have a value  "book" , and prefix have a value "bk"
Now Above are the ways is helpful for us to read the xml root element name.

No comments:

Post a Comment