top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

XML Namespace Program

0 votes

XML (Extensible Markup Language)


You can use prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by  xmlns attribute in the start tag of an element.

The namespace declaration has the following syntax. xmlns:prefix="URI".


Name Conflicts in XML

Name conflict is called two tags and has the same name to execute the first tag only. If you write the Namespace control, it conflicts.

This often results in a conflict, when trying to mix XML documents from the different XML Applications.


Default Namespace In XML

Defining a default namespace for an element saves us from using the prefixes in all the child elements. In the default namespace, you cannot write the namespace, which automatically used this namespace.


(EX: xmlns="namespaceURI")


(URI) Uniform Resource Identifier

XML language uses the URL, URI and URN. A Uniform Resource Identifier (URI) is a string of the characters, which identifies an internet resource.

The most common URI is the Uniform Resource Locator (URL), which identifies an internet domain address.

The third not so common type of URI is the Universal Resource Name (URN).



  1. <root xmlns:h="" xmlns:f="">  
  2.     <h:table>  
  3.         <h:tr>  
  4.             <h:td>Lion</h:td>  
  5.             <h:td>Tiger</h:td>  
  6.         </h:tr>  
  7.     </h:table>  
  8.     <f:table>  
  9.         <f:name>Box</f:name>  
  10.         <f:width>100</f:width>  
  11.         <f:height>120</f:height>  
  12.     </f:table>  
  13.     <root>  









posted Jan 12 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

Related Articles

XML and XPath Program: Xpath is called for finding the information within the document.


What is XPath?

  1. XPath is a syntax to define the parts of XML document.
  2. XPath uses the path expressions to navigate in XML documents.
  3. XPath contains a library of the standard functions.
  4. XPath is a major element in XSLT.
  5. XPath is also used in XQuery, XPointer and XLink.
  6. XPath is a W3C recommendation. 



XML copy Editor, XEditor. 



  1. <book>  
  2.     <title>XML</title>  
  3.     <author>Erik T. Ray</author>  
  4.     <year>2003</year>  
  5.     <price>300</price>  
  6. </book>  







Erik T. Ray










Erik T. Ray


There are many different techniques to use by which you can create an XML document in C#. One of them is LINQ to XML which we are going to discuss in this article.

Let’s say we need to create an XML as below:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Parent>  
  3. <Header>  
  4. <FileDetails>  
  5. <FileName>RandomFile</FileName>  
  6. <FileVersion>1.0</FileVersion>  
  7. </FileDetails>  
  8. </Header>  
  9. <Body>  
  10. <Infos>  
  11. <Info Type="Information1">This is Information1</Info>  
  12. <Info Type="Information2">This is Information2</Info>  
  13. </Infos>  
  14. <Users>  
  15. <UserDetails>  
  16. <Name>  
  17. <FirstName>Vipul</FirstName>  
  18.  <MiddleName/>  
  19.                     <LastName>Malhotra</LastName>  
  20.                 </Name>  
  21. <DateOfBirth>12-Apr-1990</DateOfBirth>  
  22. </UserDetails>  
  23. </Users>  
  24. </Body>  

Let’s break the creation of the file in two parts so as to be able to see more features.

We will first create the below Xml:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Parent>  
  3. <Header>  
  4. <FileDetails>  
  5. <FileName>RandomFile</FileName>  
  6. <FileVersion>1.0</FileVersion>  
  7. </FileDetails>  
  8. </Header>  
  9. <Body>  
  10. <Infos>  
  11. <Info Type="Information1">This is Information1</Info>  
  12. <Info Type="Information2">This is Information2</Info>  
  13. </Infos>  
  14. </Body>  

In order to create this, we will first define an XDocument with the parent root as below:

  1. XDocument doc = new XDocument(new XElement("Parent"));  

After this, we will use this “doc” as the root of the file and will writing nested XElement to it.

Let’s first create the Header portion of the xml.
Please notice that the XElement “Header “ is added as a new element and the further elements are added as nested to this “Header” element. It is due to the reason that the elements are sub-elements of “Header”. Further “FileName” and “FileVersion” element is a sub-element of “FileDetails”

In the same way, we would add another section to the root of the doc. This section would be “Body”. 

The code for the same would be as:
This follows the same logic that “Body” is also sub-node of the root “parent” and so it is added directly to the root. Whereas , the element “Infos” is sub-element of “Body” and is so added in the way above. Same goes for “Info” which is a further sub-element of “Infos”. 

Also notice how an attribute is added to each of the “Info” element using XAttribute.

After this, we further need to add the below section as sub-nodes of “Body” and not the root of the application:

  1. <Users>  
  2. <UserDetails>  
  3. <Name>  
  4. <FirstName>Vipul</FirstName>  
  5.  <MiddleName/>  
  6.                     <LastName>Malhotra</LastName>  
  7.                 </Name>  
  8. <DateOfBirth>12-Apr-1990</DateOfBirth>  
  9. </UserDetails>  
  10. </Users>  

In order to do that, we would make sure that the code starts appending the code inside the “Body” tag of the already created xml.

Using XDocument, we can search for the node “Body” and then start adding node XElements to it .
Searching a node Is done using:

Further adding more elements to it is done using the below code:
The logic behind the hierarchy is the same as that discussed above.

The code can also be used inside a loop in case we need to add many similar sections to a particular node. Like in this case there can be many users and all of their details would have to be added in different UserDetails section inside the “Body” node.



In today's tech world, most of the applications being developed under Logistics, Inventory, Internal Transaction and other domains require day-to-day data in excel files and prefer excel file operations in their applications.

I will be sharing one of the Nuget Package tools which, with very minimal lines of code, will export an excel file for us.

The Tool is Closed XML.

Just write a few lines of code and done! It is developer friendly. If we have used the Open XML, there are a lot of lines of code which are required to export an excel from data. We can create an excel file of 2007/2010 configuration without an Excel application.

To add the closed XML package, we add it directly through the user interface from the Nuget Gallery and also, we can use the Package Manager console to add the package using the below command

PM> Install-Package ClosedXML


  1. DataTable dt = new DataTable();  
  2. dt.Columns.AddRange(new DataColumn[3]  
  3. {  
  4.  new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string))  
  5. });  
  6. dt.Rows.Add(1, "C Sharp corner", "United States");  
  7. dt.Rows.Add(2, "Suraj", "India");  
  8. dt.Rows.Add(3, "Test User", "France");  
  9. dt.Rows.Add(4, "Developer", "Russia"); //Exporting to Excel               
  10. string folderPath = "C:\\Excel\\";              
  11. if (!Directory.Exists(folderPath))              
  12. {                   
  13.     Directory.CreateDirectory(folderPath);            
  14. }     
  15. //Codes for the Closed XML             
  16.     using (XLWorkbook wb = new XLWorkbook())              
  17.     {                
  18.         wb.Worksheets.Add(dt, "Customers");                  
  19.         //wb.SaveAs(folderPath + "DataGridViewExport.xlsx");                
  20.         string myName = Server.UrlEncode("Test" + "_" + DateTime.Now.ToShortDateString() + ".xlsx");        
  21.         MemoryStream stream = GetStream(wb);  
  22.         // The method is defined below             
  23.         Response.Clear();                  
  24.         Response.Buffer = true;              
  25.         Response.AddHeader("content-disposition", "attachment; filename=" + myName);         
  26.         Response.ContentType = "application/";           
  27.         Response.BinaryWrite(stream.ToArray());                
  28.         Response.End();  
  29.     }  

The above code instantiates a data table, with few data initializations.

  1. public MemoryStream GetStream(XLWorkbook excelWorkbook)   
  2. {  
  3.     MemoryStream fs = new MemoryStream();  
  4.     excelWorkbook.SaveAs(fs);  
  5.     fs.Position = 0;  
  6.     return fs;  
  7. }

We are using this method, so as to return a stream in order to download the file in response to using the stream. The save as method of the Closed XML helps create the stream.

Downloaded file looks like below,


  1. XML document has a single root node.
  2. The tree is a general ordered tree.
  3. A parent node may have any number of children.
  4. Child nodes are ordered and may have siblings.
  5. Preorder traversals are usually used to get the information, out of the tree.


Simple XML Document

  1. <?xml version = “1.0” ?> <address>  
  2. <name>  
  3. <first>Alice</first></br>  
  4. <last>Lee</last></br>  
  5. </name>  
  6. <email></email></br>  
  7. <phone>123-45-6789</phone></br>  
  8. <birthday>  
  9. <year>1983</year></br>  
  10. <month>07</month></br>  
  11. <day>15</day>  
  12. </birthday>  
  13. </address>  

Program Demo 

Write the code from XMLCopyEditor.

Save Any Location(EX:Sample.xml). 






What is XML?

  1. XML stands for Extensible Markup Language.
  2. XML is a markup language much like HTML.
  3. XML was designed to carry the data but not to display it.
  4. XML tags are not predefined. You must define your own tags.
  5. XML is designed to be self-descriptive.

Why XML is popular?

  1. Our machines are now only capable of processing requirements of this data format.
  2. It supports data processing, data storage, and bandwidth requirements for the exchange of XML documents.
  3. Driving force for the use of a technology, like XML, is the desire to exchange information in Open Systems or Open Software.
  4. Development of the internet.


  1. XML is text (Unicode) based; Takes up less space; Can be transmitted efficiently.
  2. One XML document can be displayed differently in different media, like HTML, video, CD, DVD. You only have to change the XML document in order to change all the rest.
  3. XML documents can be modularized and its parts can be reused.

SGML (Standard Generalized Markup Language)

  1. Forefather of all markup languages.
  2. In 1969, it Introduced the notion that data processing and document processing could be one and the same thing.
  3. Introduced the notion of a generalized document format.
  4. SGML specification can communicate between systems.
  5. Provides DTD specification to improve the standard of the document.

Example of an HTML Document

  1. <html>  
  2. <head><title>Example</title></head.  
  3. <body>  
  4. <h1>This is an example of a page.</h1>  
  5. <h2>Some information goes here.</h2>  
  6. </body>  
  7. </html>  


Write the HTML code in notepad and save it with .html extension(EX:sample.html). Click the file to run in the browser.



  1. <?xml version=“1.0”/>  
  2. <mymessage>  
  3. <message> Welcome to XML </message>  
  4. </mymessage>  

An XML document contains one root element and its child elements.

Example of an XML Document

  1. <?xml version=“1.0”/>  
  2. <address>  
  3. <name>Alice Lee</name>  
  4. <email></email>  
  5. <phone>212-346-1234</phone>  
  6. <birthday>1985-03-22</birthday>  
  7. </address>  


The XML code will be written in the XML copy editor. Save it at any location (EX:text.xml). Click it and open in the browse.



output(The XML program output)



Difference Between HTML and XML 

  1. HTML tags have a fixed meaning and browsers know what it is while the XML tags are different for different applications, and users know what they mean.
  2. HTML tags are used for display while the XML tags are used to describe the documents and the data.

Benefits of XML

  1. Simplifies Data Sharing.
  2. Simplifies Data Transport.
  3. Simplifies Platform Changes.
  4. Separates Data from HTML.
  5. Makes Your Data More Available.
  6. Represents the information and the metadata about the information.
  7. XML is referred as future-proof or loosely coupled, since it has the capability of separating process and data content.
  8. XML is used to create new internet languages.

Well-Formed Documents

  1. An XML document is said to be well-formed if it follows all the rules.
  2. An XML parser is used to check that all the rules have been obeyed.
  3. Parser is a software to process XML Document.
  4. It reads the XML Document, Checks its syntax, reports errors and allows programmatic access to documents contents.
  5. XML document is considered well formed if the syntax is correct.
  6. Single root, start and end tag, attribute values in quotes.
  7. Recent browsers such as Internet Explorer 5 and Netscape 7 come with XML parsers.
  8. Parsers are also available for free download over the Internet. One is Xerces, from the Apache open-source project.
  9. Java 1.4 also supports an open-source parser.

Advantages of xml over sgml

  1. Though XML is using most of the functionality in SGML, it provides a number of distinct advantages.
  2. XML permits well-formed documents to be parsed without the need for a DTD, whereas SGML implementations require some DTD for processing
  3. XML is much simpler and more permissive in its syntax than SGML.
  4. Implementation of SGML over the internet is more difficult than in XML.

Advantages of XML over HTML (and differences)

  1. XML is not a replacement for HTML.
  2. XML and HTML were designed with different goals:
  3. XML was designed to transport and store data, with focus on what data is.
  4. HTML was designed to display data, with focus on how data looks.
  5. HTML is about displaying information, while XML is about carrying information.

Advantages of xml over EDI(Electronic Data Interchange)

  1. XML requires less cost for data transaction and maintenance than EDI (which uses Millions of dollars for transactions).
  2. XML uses Internet for data exchange whereas EDI over Internet does not meet much success.
  3. XML has many built in components like validity checking, data mapping, Extensible style sheet etc.,
  4. XML supports internationalization and localization but EDI doesn’t provide it.

Drawbacks of XML

  1. XML is huge – takes lot of space to represent data (3 to 20 times greater than file formats).
  2. XML editors often lack the detail and helpfulness found in common EDI editors.


  1. A well-formed document has a tree structure and obeys all the XML rules.
  2. A particular application may add more rules in either a DTD (document type definition) or in a schema.
  3. Many specialized DTDs and schemas have been created to describe particular areas.
  4. These range from disseminating news bulletins (RSS) to chemical formulas.
  5. DTDs were developed first, so they are not as comprehensive as schema.

Thanks for reading.


In this article, I am going to give you the best way to access XML data from an XML document and also how to find the common record node count.


  1. <Data>  
  2.     <Student Name="Saravanan"// Node with same name  
  5.         <Address>Address1</Address>  
  6.         <SurName> SurName1  
  7.         </ SurName>  
  8.         <City>City1</City>  
  9.         <State>State1</State>  
  10.     </Student>  
  11.     <Student Name="Mohan">  
  12.         <SurName> SurName2  
  13.         </ SurName>  
  14.         <Address>Address2</Address>  
  15.         <City>City2</City>  
  16.         <State>State2</State>  
  17.     </Student>  
  18.     <Student Name="Fayaz">  
  19.         <SurName> SurName3  
  20.         </ SurName>  
  21.         <Address>Address3</Address>  
  22.         <City>City3</City>  
  23.         <State>State3</State>  
  24.     </Student>  
  25.     <Student Name="Siva">  
  26.         <SurName> SurName4  
  27.         </ SurName>  
  28.         <Address>Address4</Address>  
  29.         <City>City4</City>  
  30.         <State>State4</State>  
  31.     </Student>  
  32.     <Student Name="Saravanan"// Node with same name  
  35.         <Address>Address5</Address>  
  36.         <SurName> SurName5  
  37.         </ SurName>  
  38.         <City>City5</City>  
  39.         <State>State5</State>  
  40.     </Student>  
  41. </Data>  

Step 1

Before we do anything with the XML document, we have to first load the XML file. The following code is the common way to load a XML document.


Before dealing with XML, initilize the XML Namespace, i.e., using system.xml;

  1. XMLDocument  StudentDocument = new xmlDocument();  
  2. studentDocument("give the XML Documnet Path here e.g C://Studentrecords/Student.xml");  

Step 2

Now, we are going to access the XML data from XML document by using XPath.


XPath is used to navigate through elements and attributes in an XML document. In other words, XPath uses the path expressions to select nodes or node-sets in an XML Document.

Here is the code:

By using XmlNode keyword, we can access the node value.


  1. XmlNode Singlenode=StudentDocument.SelectSingleNode("XPath here E.g /Data/Students/Student[@ Name='Mohan']/Address "); // accessing one student record  


Still, the data is in XML format. So we assign the node value to another string variable so that the value can be used for further purpose.


  1. string StudentAddress= Singlenode.InnerText;  

Now, consider the situation of needing to get the correct data from XML document if two students have the same name. Then, by comparing the surname, we can get the correct data. Try the following code.


Consider the above XML document. It has two nodes with the same name "Saravanan".

  1. <Student Name="Saravanan"// Node with same name  
  2.     <Address>Address1</Address>  
  3.     <SurName> SurName1</ SurName>  
  4.         <City>City1</City>  
  5.         <State>State1</State>  
  6. </Student>  
  7. <Student Name="Saravanan"// Node with same name  
  8.     <Address>Address5</Address>  
  9.     <SurName> SurName5</ SurName>  
  10.         <City>City5</City>  
  11.         <State>State5</State>  
  12. </Student>  


User input is---- Student Name - Saravanan and SurName-SurName5

To find the number of nodes with the same value, try the following code.


  1. XmlNodeList Lists = Students.SelectNodes(" /Data/Students/Student[@ Name='Saravanan']/Address ");  

Note: For getting a single node value, we use "XmlNode" Keyword, but for finding more than one nodes with the same value, we have to use "XmlNodeList".

  1. if (Lists.count > 1) {  
  2.     //if this loop is executes ,mean there is morethan one node with same value  
  3.     foreach(XmlNode List in Lists) {  
  4.         //this loop is for comparing the surname to get correct node value  
  5.         SingleNodeSurName = StudentDocument.SelectSingleNode("XPath here E.g /Data/Students/Student[@ Name='Mohan']/SurName ").InnerText;  
  6.         //Now compare the Address with user input address  
  7.         if (SingleNodeSurName.toUpper() == UserInputSurName.toUpper()) {  
  8.             //if two Surname is same it get all other data's by the same above method  
  9.             Address,  
  10.             City,  
  11.             State  
  12.         }  
  13.     }  
  14. }  

I hope this article is very useful. Thank You.


This article describes how to transform the XML output of SQL query statements using FOR XML AUTO to HTML using XSLT.

Normally, we execute the query using ExecuteNonQuery statement and fill the output into a data table. We can access the data in the data table by giving column name and row number in the looping method. This makes us work on extra coding and takes a lot of time to get the correct data from executed query. So, I moved to XML because, in XML, we can fetch the values easily and quickly without writing too much code.     

FOR XML Clause in SQL

Basically, we have four types of FOR XML clause in SQL.


Each of the above types satisfies its own need. When you want full control over the produced XML, you use FOR XML EXPLICIT, but it is difficult to understand, read, or maintain. FOR XML AUTO produces the most readable SELECT statement. The RAW option is rarely used and therefore not discussed. The PATH option allows you to mix attributes and elements easier. Here, I gona use FOR XML AUTO.

Table Name - Contact_Details


If we want the output as in XML format, we need to add the FOR XML AUTO statement.


  1. SELECT * FROM Contact_Details FOR XML AUTO  

This query gives the output like,

  1. < Contact_Details Contact_ID=’001’ Contact_Number=’ 088888888’ Contact_Name=’Mohan’ Contact_Location=’Chennai’/>  
  2. < Contact_Details Contact_ID=’002’ Contact_Number=’ 099999999’ Contact_Name=’Abilash’ Contact_Location=’Bangalore’/>  

The XML which we got in output is not in user-friendly format. We need each field as an attribute so, that we can access the values using XPATH. To achieve that, we need to add the ELEMENTS parameter with the query.



This query gives the output like,

  1. < Contact_Details>  
  2.     <Contact_ID>001</Contact_ID>  
  3.     <Contact_Number>088888888</Contact_Number>  
  4.     <Contact_Name>Mohan</Contact_Name>  
  5.     <Contact_Location>Chennai</Contact_Location>  
  6. </ Contact_Details>  
  7. < Contact_Details>  
  8.     <Contact_ID>002</Contact_ID>  
  9.     <Contact_Number>099999999</Contact_Number>  
  10.     <Contact_Name>Abilash</Contact_Name>  
  11.     <Contact_Location>Bangalore</Contact_Location>  
  12. </ Contact_Details>  

So, this is the exact XML format we need.

Now, we are going to create XML DOCUMENT and write this output XML into that XML document in coding. To read the query in XML format, we need to execute the query using ExecuteXmlReader() function. 

  1. XmlReader XMLReader = new XmlReader();  
  2. XmlDocument XmlDoc = new XmlDocument();  
  3. SqlCommand Cmd = new SqlCommand(Query, Conn);  
  4. XMLReader = cmd.ExecuteXmlReader();  
  5. XPathDocument xPathDoc = new XPathDocument(XMLReader);  
  6. XPathNavigator xPathNavi = xPathDoc.CreateNavigator();  
  7. XmlDoc.LoadXml(XpathNavi.OuterXml);  

Now, we got the full structured XML Document. Using this, we will transform the data into HTML format using XSLT.

Before transforming, we need to create one XSLT file to assign the values from XMLDocument to HTML format.


  1. <?xml version=”1.0” encoding=”utf-8”?>  
  2. <xsl:stylesheet version=”1.0” xmlns:xsl=””>  
  3.     <xsl:output method=”xml” indent=”yes” omit-xml-declaration=”yes”>  
  4.         <xsl:template match=”/*”>  
  5.             <table>  
  6.                 <tr>// Column heading  
  7.                     <td>ContactID</td>  
  8.                     <td>ContactNumber</td>  
  9.                     <td>ContName</td>  
  10.                     <td>ContactLocation</td>  
  11.                 </tr>  
  12.                 <xsl:for-each select=”/ Contact_Details”>  
  13.                     <tr>// inserting XML data into HTML table  
  14.                         <td>  
  15.                             <xsl:value-of select=”/Contact_details/Contact_ID” </td> // using XPath we can access the value from XML Document  
  16.                                 <td>  
  17.                                     <xsl:value-of select=”/Contact_details/Contact_Number” </td>  
  18.                                 <td>  
  19.                               <xsl:value-of select=”/Contact_details/Contact_Name” </td>  
  20.                           <td>  
  21.                        <xsl:value-of select=”/Contact_details/Contact_Location” </td>  
  22.                     </tr>  
  23.                 </xsl:for-each>  
  24.             </table>  
  25.         </xsl:template>  
  26. </xsl:stylesheet>  

Now, we have XML Document and XSLT file. In the next step, we are going to transform the XML Document into HTML using XSLT. To do this, we pass the XMLDocument and XSLT file to separate functions and get fully formed HTML strings in return.

  1. Public static string TransformXMLTOHTML(XmlDocument XMLDoc, String XSLTFilename) {  
  2.     StringWriter HTMLString = new StringWriter();  
  3.     XslCompiledTransform Xmltransform = new XslCompiledTransform();  
  4.     XmlTransform.Load(XSLTFilename); // Load XSLT File  
  5.     Xmltranform.Transform(XMLDoc, null, Result); // transform XML into HTML  
  6.     Return HTMLString.ToString();  
  7. }  
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.