Create XML Doc in C#

Lakhangarg
Posted by Lakhangarg under C# category on | Views : 6152
This Sample code will show you how to create a XML document using C#.
Suppose we have Data like:

PublisherName: Wrox
Book Subject: ASP.NET
Book Title:
(1) Beginning ASP.NET MVC 1.0
(2) Silverlight 3 Programmer's Reference
(3) Professional Refactoring in C# & ASP.NET

Book Subject: SQL Server
Book Title:
(1) Beginning Microsoft SQL Server 2008 Administration
(2) Professional LINQ

And we want to show this data in XML format:

Sample Code to show above Data into XMl Format:

XmlDocument xDoc = new XmlDocument();
XmlNode ndRootNode = xDoc.CreateElement("BookData");
xDoc.AppendChild(ndRootNode);

XmlNode ndPublisher = xDoc.CreateElement("Publisher");
XmlAttribute atName = xDoc.CreateAttribute("Name");
atName.Value = "Wrox";
ndPublisher.Attributes.Append(atName);
ndRootNode.AppendChild(ndPublisher);

XmlNode ndBookSubject1 = xDoc.CreateElement("Subject");
XmlAttribute atSubject1 = xDoc.CreateAttribute("Name");
atSubject1.Value = "ASP.NET";
ndBookSubject1.Attributes.Append(atSubject1) ;
ndPublisher.AppendChild(ndBookSubject1);

XmlNode ndBookTitle1 = xDoc.CreateElement("Title");
ndBookTitle1.AppendChild(xDoc.CreateCDataSection("Beginning ASP.NET MVC 1.0"));
ndBookSubject1.AppendChild(ndBookTitle1);

XmlNode ndBookTitle2 = xDoc.CreateElement("Title");
ndBookTitle2.AppendChild(xDoc.CreateCDataSection("Silverlight 3 Programmer's Reference"));
ndBookSubject1.AppendChild(ndBookTitle2);

XmlNode ndBookTitle3 = xDoc.CreateElement("Title");
ndBookTitle3.AppendChild(xDoc.CreateCDataSection("Professional Refactoring in C# & ASP.NET"));
ndBookSubject1.AppendChild(ndBookTitle3);

XmlNode ndBookSubject2 = xDoc.CreateElement("Subject");
XmlAttribute atSubject2 = xDoc.CreateAttribute("Name");
atSubject2.Value = "SQL Server";
ndBookSubject1.Attributes.Append(atSubject2);
ndPublisher.AppendChild(ndBookSubject2);

XmlNode ndBookTitle4 = xDoc.CreateElement("Title");
ndBookTitle4.AppendChild(xDoc.CreateCDataSection("Beginning Microsoft SQL Server 2008 Administration"));
ndBookSubject2.AppendChild(ndBookTitle4);

XmlNode ndBookTitle5 = xDoc.CreateElement("Title");
ndBookTitle5.AppendChild(xDoc.CreateCDataSection("Professional LINQ"));
ndBookSubject2.AppendChild(ndBookTitle5);


Output:

<BookData>
<Publisher Name="Wrox">
<Subject Name="SQL Server">
<Title>Beginning ASP.NET MVC 1.0</Title>
<Title>Silverlight 3 Programmer's Reference</Title>
<Title>Professional Refactoring in C# & ASP.NET</Title>
</Subject>
<Subject>
<Title>Beginning Microsoft SQL Server 2008 Administration</Title>
<Title>Professional LINQ</Title>
</Subject>
</Publisher>
</BookData>

The CreateCDataSection
xDoc.CreateCDataSection("Beginning Microsoft SQL Server 2008 Administration")
is used to write the data in CData Section

For More details Visit: http://lakhangarg.blogspot.com

Comments or Responses

Login to post response