dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online Membersvenkata raju
Saranya
Amruta
Minu
navas
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » .NET programming » XML

To create Xml using xmldocument,xmlwriter and xmltextreader


Posted Date:     Category: XML    
Author: Member Level: Gold    Points: 40


There are various methods of creating an xmldocument and they are as follows a)using Xmldocument b)using xmlwriter c)Using xmltextwriter The XmlDocument is a read/write consisting of a tree of XML nodes in memory. One can perform as many edits as possible anywhere in the document prior to writing it out to a stream,whereas XmlWriter is a write-only object which helps to write a well-formed XML to a stream. There are no read capabilities and the write capabilities are forward-only as well



 


Different Mehtods of creating Xml tags using .net


There are various methods of creating xml tags and the following are mentioned below
a)Using Xmldocument class
b)Using Xml Writer
c)Using xml Text Writer


Using XML Document


Using the xml document is a bit more slow process when compared to either xmlwriter or xmltextwriter and
it involves more object oriented work when compared to xmlwriter,Firstly the xmldocument is instantiated and the root nodes are created
using createelement() method similarly the attributes for the nodes can be created using CreateAttribute() methods,Each time after creating the
node and the attribute it has to appended to the document using the Append() method on the Attributes property.Finally, After creating the nodes the document is
saved using the Save method.

Sample Code


The code given below is an example of creating xml using xmldocument


public void createNodes()
{
XmlDocument XDoc = new XmlDocument();
// Create root node.
XmlElement XElemRoot = XDoc.CreateElement("Employee");
//Add the node to the document.
XDoc.AppendChild(XElemRoot);
XmlElement Xsource = XDoc.CreateElement("EmployeeDetails");
XElemRoot.AppendChild(Xsource);
XmlElement XTemp = XDoc.CreateElement("EmpId");
XTemp.InnerText = "1";
Xsource.AppendChild(XTemp);
XTemp = XDoc.CreateElement("EmpName");
XTemp.InnerText = "Test Name";
Xsource.AppendChild(XTemp);
XTemp = XDoc.CreateElement("Designation");
XTemp.InnerText = "Test Desig";
Xsource.AppendChild(XTemp);
XDoc.Save(@"D:\temp\xmlfile.xml");
}

Using Xml Writer


Xmlwriter,An abstract class which is used to write xml data from objects in memory,Providing fast,forward
only,non-cached methods of generating files containing XML data.
The xmlwriter is created by initializing it as follows

XmlWriter xmlWriter = XmlWriter.Create("test.xml");

To create the root element the keywords WriteStartDocument(),WriteStartElement("Employees") are used
further,the keyword WriteWhitespace is used which is used to form the tag in the appropriate position
The inner text for each tags were formed using WriteString method

refer the sample code on creating a xml file using xmlwriter


public void createNodeWriter()
{

string sConnection = ConfigurationSettings.AppSettings.Get("Dsn");//reading the connection from the app.configfile
SqlConnection strCon = new SqlConnection(sConnection);
strCon.Open();
SqlDataAdapter da = new SqlDataAdapter("select top 10 name,email,phonenumber,city from tableName order by empid desc", strCon);
DataTable dt = new DataTable();
da.Fill(dt);
strCon.Close();

XmlWriter xmlWriter = XmlWriter.Create("test.xml");
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("EmpDetails");
xmlWriter.WriteWhitespace("\n");

for (int i = 0; i < dt.Rows.Count; i++)
{
xmlWriter.WriteStartElement("EmployeeInfo");
xmlWriter.WriteWhitespace("\n");
//xmlWriter.WriteAttributeString("age", "42");
xmlWriter.WriteStartElement("Name");
xmlWriter.WriteString(dt.Rows[i]["name"].ToString().Trim());
xmlWriter.WriteEndElement();
xmlWriter.WriteWhitespace("\n");
xmlWriter.WriteStartElement("Email");
xmlWriter.WriteString(dt.Rows[i]["email"].ToString().Trim());
xmlWriter.WriteEndElement();
xmlWriter.WriteWhitespace("\n");
xmlWriter.WriteStartElement("Phonenumber");
xmlWriter.WriteString(dt.Rows[i]["phonenumber"].ToString().Trim());
xmlWriter.WriteEndElement();
xmlWriter.WriteWhitespace("\n");
xmlWriter.WriteStartElement("City");
xmlWriter.WriteString(dt.Rows[i]["city"].ToString().Trim());
xmlWriter.WriteEndElement();
xmlWriter.WriteWhitespace("\n");
xmlWriter.WriteEndElement();
xmlWriter.WriteWhitespace("\n");
}

xmlWriter.WriteEndDocument();
xmlWriter.Close();
}

Using Xml Text Writer


Both xmlwriter and xmltextwriter are defined in the namespace system.Xml,Besides they do have some diffetences and they are as follows
Xmlwriter is an abstractclass and XmlTextWriter is a specific implementation of XmlWriter.Also,the xmltextwriter is used to create forward
only,non-cached methods of generating files containing XML data

below is the sample code to create xml using xmltextwriter


public void createTextNodeWriter()
{
string sConnection = ConfigurationSettings.AppSettings.Get("defaultDsn");
SqlConnection strCon = new SqlConnection(sConnection);
strCon.Open();
SqlDataAdapter da = new SqlDataAdapter("select top 10 name,email,phonenumber,city from TableName order by empid desc", strCon);
DataTable dt = new DataTable();
da.Fill(dt);
strCon.Close();


using (XmlTextWriter xmlTxtWriter = new XmlTextWriter("C:\\temp\\Test.xml", null))
{
xmlTxtWriter.WriteStartDocument();
xmlTxtWriter.WriteStartElement("EmpDetails");
xmlTxtWriter.WriteWhitespace("\n");
for (int i = 0; i < dt.Rows.Count; i++)
{
xmlTxtWriter.WriteStartElement("EmployeeInfo");
xmlTxtWriter.WriteWhitespace("\n");
xmlTxtWriter.WriteStartElement("Name");
xmlTxtWriter.WriteString(dt.Rows[i]["name"].ToString().Trim());
xmlTxtWriter.WriteEndElement();
xmlTxtWriter.WriteWhitespace("\n");
xmlTxtWriter.WriteStartElement("Email");
xmlTxtWriter.WriteString(dt.Rows[i]["email"].ToString().Trim());
xmlTxtWriter.WriteEndElement();
xmlTxtWriter.WriteWhitespace("\n");
xmlTxtWriter.WriteStartElement("Phonenumber");
xmlTxtWriter.WriteString(dt.Rows[i]["phonenumber"].ToString().Trim());
xmlTxtWriter.WriteEndElement();
xmlTxtWriter.WriteWhitespace("\n");
xmlTxtWriter.WriteStartElement("City");
xmlTxtWriter.WriteString(dt.Rows[i]["city"].ToString().Trim());
xmlTxtWriter.WriteEndElement();
xmlTxtWriter.WriteWhitespace("\n");
xmlTxtWriter.WriteEndElement();
xmlTxtWriter.WriteWhitespace("\n");
}
xmlTxtWriter.WriteEndDocument();
xmlTxtWriter.Close();
}
}


Difference between XmlDocument vs XmlWriter

The XmlDocument is a read/write consisting of a tree of XML nodes in memory.
One can perform as many edits as possible anywhere in the document prior to writing it out to a stream,whereas
XmlWriter is a write-only object which helps to write a well-formed XML to a stream.
There are no read capabilities and the write capabilities are forward-only as well





Did you like this resource? Share it with your friends and show your love!


Responses to "To create Xml using xmldocument,xmlwriter and xmltextreader"

No responses found. Be the first to respond...

Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: XML Validation with XSD along with Custom Exception
    Previous Resource: How to check whether element value at any XPath is alphanumeric or not.
    Return to Resources
    Post New Resource
    Category: XML


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Xml  .  Xmldocuments  .  Xmltextwriter  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.