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"
<Employees>
<Employee>
    <Name>Rajesh</Name>
</Employee>
</Employees>

 First way
XDocument

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

 Second way  
XmlDocument

            XmlDocument xdoc=new XmlDocument();
            xdoc.Load("sample.xml");
       
            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='urn:loc.gov:books'
         xmlns:isbn='urn:ISBN:0-395-36341-6'>
    <bk:title>Cheaper by the Dozen</bk:title>
    <isbn:number>1568491379</isbn:number>
</bk:book>
           
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

             XmlTextReader reader=new XmlTextReader("sample.xml");
            while(reader.Read())
            {
                if(reader.HasValue)
                {
                    if(reader.IsStartElement())
                    {
                        string rootelename=reader.LocalName;
                        string prefix=reader.Prefix;
                        break;                    
                    }
                }
        
            }

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