top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

XML Creation using LINQ to XML

0 votes
447 views

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.
Header
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:
code
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 .
node 
Searching a node Is done using:

Further adding more elements to it is done using the below code:
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.

posted Jan 16, 2018 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

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.

  • FOR XML RAW
  • FOR XML AUTO
  • FOR XML EXPLICIT
  • FOR XML PATH

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

Contact_IDContact_NumberContact_NameContact_Location
001088888888MohanChennnai
002099999999AbilashBangalore


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.

 

  1. SELECT * FROM Contact_Details FOR XML AUTO, ELEMENTS  

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.

Contact_Details.xslt

  1. <?xml version=”1.0” encoding=”utf-8”?>  
  2. <xsl:stylesheet version=”1.0” xmlns:xsl=”http://www.w3.org/1999/XSL/Tranform”>  
  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. }  
READ MORE

Introduction

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

Snippet

  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/vnd.ms-excel";           
  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,

file

READ MORE

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. 

Softwares

 

XML copy Editor, XEditor. 

 

Program  

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

Xpath

 

/book 

 

output
 

XML

Erik T. Ray

2003

300

 

Xpath

 

/book/author

 

output

 

Erik T. Ray

READ MORE

In this article, I'm going to use XML RAW type to get XML format output from the data of two tables. Here, a question may rise, why can’t we do that by XML AUTO type. Yes, we can. But when we using XML AUTO, the output XML will consist too many XML nodes and there is no order in the XML nodes when we use JOIN statement in the query when we use two tables in single query. You can understand this in the following explanation.

Table: Student_Details

Student_IDContact_NumberStudent_NameStudent_Location
001088888888MohanChennai
002099999999AbilashBangalore


Table: Student_Marks 
 

Student_IDExam_TypeScored_MarkScored_Percentage
001AnnualExam110086
002AnnualExam105080

So, these are my tables. The first table has the basic information about students while the second table has the marks details.

Here, our task is to get the information about the students and attach the marks details with each student, based on the StudentID because here, StudentID is the primary key for both tables. This can be done in different ways. I am going to do that using XML Raw elements.

Let’s write the query to select the values using XML AUTO elements.

 

  1. SELECT Student_ID,Contact_Number,Student_Name,Student_Location,MarkDetails.Exam_Type AS ExamType,MarkDetails.Scored_Mark AS Marks,MarkDetails.Scored_Percentage AS Percentage FROM Student_Details LEFT JOIN Student_Marks AS MarkDetails ON MarkDetails.Student_ID=Student_ID for XML AUTO,ELEMENT  

This query will give output like the following.

  1. < Student_Details>  
  2.     < Student_ID>001  
  3.         < /Student_ID>  
  4.             < Contact_Number>088888888  
  5.                 < /Contact_Number>  
  6.                     < Student_Name>Mohan  
  7.                         < /Student_Name>  
  8.                             < Student_Location>Chennai  
  9.                                 < /Student_Location>  
  10.                                     < ExamType>  
  11.                                         < ExamType>AnnualExam</ ExamType>  
  12.                                         < Marks>  
  13.                                             < Marks>1100</ Marks>  
  14.                                             < Percentage>  
  15.                                                 < Percentage>86</ Percentage>  
  16.                                             </ Percentage>  
  17.                                         </ Marks>  
  18.                                     </ ExamType>  
  19.                                 </ Student_Details>  
  20.                                 < Student_Details>  
  21.                                     < Student_ID>002  
  22.                                         < /Student_ID>  
  23.                                             < Contact_Number>099999999  
  24.                                                 < /Contact_Number>  
  25.                                                < Student_Name>Abilash  
  26.                                               < /Student_Name>  
  27.                                            < Student_Location>Bangalore  
  28.                                          < /Student_Location>  
  29.                                       < ExamType>  
  30.                                     < ExamType>AnnualExam</ ExamType>  
  31.                                   < Marks>  
  32.                                < Marks>1050</ Marks>  
  33.                             < Percentage>  
  34.                          < Percentage>80</ Percentage>  
  35.                      </ Percentage>  
  36.                </ Marks>  
  37.        </ ExamType>  
  38.  </ Student_Details>  

The output XML format is not what we have expected. To overcome this, we are moving to XML RAW type method to get the well designed XML with root node.

Let's try the same query with XML RAW Type.

 

  1. SELECT Student_ID,Contact_Number,Student_Name,Student_Location,MarkDetails.Exam_Type AS ExamType,MarkDetails.Scored_Mark AS Marks,MarkDetails.Scored_Percentage AS Percentage FROM Student_Details LEFT JOIN Student_Marks AS MarkDetails ON MarkDetails.Student_ID=Student_ID for XML RAW(‘Student’),ELEMENTS,TYPE  

This query will produce the output like following.

  1. < Student>  
  2.       < Student_ID>001< /Student_ID>  
  3.          < Contact_Number>088888888< /Contact_Number>  
  4.             < Student_Name>Mohan< /Student_Name>  
  5.                < Student_Location>Chennai< /Student_Location>  
  6.                   < ExamType>AnnualExam</ ExamType>  
  7.                      < Marks>1100</ Marks>  
  8.                      Percentage>86</ Percentage>  
  9.                   </ Student>  
  10.                   < Student>  
  11.                < Student_ID>002< /Student_ID>  
  12.             < Contact_Number>099999999< /Contact_Number>  
  13.          < Student_Name>Abilash< /Student_Name>  
  14.       < Student_Location>Bangalore< /Student_Location>  
  15.       < ExamType>AnnualExam</ ExamType>  
  16.       Marks>1050</ Marks>  
  17.      < Percentage>80</ Percentage>  
  18. </ Student>  

The output XML which we got now is well-formatted XML Document and in more user understandable form.

By using this, we can do more process in coding. Please refer my previous article where I have given how to transform the constructed XML into HTML document using XSLT.

I hope this article is useful.

READ MORE
...