Windows Phone Developers

Wednesday, September 17, 2008

Create XML Files using .NET / Create XML Files using C#

Writing XML Files using C#

C# has many methods to create XML files with ease. XMLTextWriter class is an useful one containing methods to create a formatted and valid XML.

It represents a writer that provides a fast, non-cached, forward-only way of generating streams or files containing XML data that conforms to the W3C Extensible Markup Language (XML) 1.0 and the Namespaces in XML recommendations

private void write2XML()

{

// Sample Invoice for Ganesh Padmavathy GmBH.

XmlTextWriter Writer = new XmlTextWriter(@"c:\ShasurData\ForBlogger\Sample.xml",Encoding.ASCII );

// Write XML with Indent

Writer.Formatting = Formatting.Indented;

// Write XML Declaration

Writer.WriteStartDocument(true);

// Writing Comments in XML File

Writer.WriteComment("Sample Invoice for GP GmbH");

// Root Element

Writer.WriteStartElement("Invoice");

Writer.WriteAttributeString("INVNo", "INT03456");

Writer.WriteAttributeString("InvDate", DateTime.Now.ToString() );

Writer.WriteStartElement ("Items");

Writer.WriteStartElement("Item");

//Writer.WriteString("Sample String");

Writer.WriteElementString("Name", "Hex Socket Screw");

Writer.WriteElementString("Price", "$0.25");

Writer.WriteElementString("Quantity", "1000");

Writer.WriteEndElement(); // Item End Tag

Writer.WriteStartElement("Item");

Writer.WriteElementString("Name", "Roll Bearing");

Writer.WriteElementString("Price", "$0.15");

Writer.WriteElementString("Quantity", "1200");

Writer.WriteEndElement(); // Item End Tag

Writer.WriteEndElement(); // Items End Tag

Writer.WriteEndElement(); // Invoice End Tag

Writer.WriteEndDocument();

Writer.Flush();

Writer.Close();

}

Write NameSpace of XML Specification in C#

Writer.WriteStartDocument(true) is used to write the XML declaration with the version "1.0".

Create Indented XML Files using C#

XmlTextWriter..::.Formatting Property is used to create XML Documents with proper indentation .

Writer.Formatting = Formatting.Indented;

Will give a indented XML as shown below

< ?xml version="1.0" encoding="us-ascii" standalone="yes"? >

< !--Sample Invoice for GP GmbH-- >

< Invoice INVNo="INT03456" d1p1:vbadud="15-09-2008 08:41:42" xmlns:d1p1="InvDate" >

< Items >

< Item >

< Name >Hex Socket Screw< /Name >

< Price >$0.25< /Price >

< Quantity >1000< /Quantity >

< /Item >

< Item >

< Name >Roll Bearing< /Name >

< Price >$0.15< /Price >

< Quantity >1200< /Quantity >

< /Item >

< /Items >

< /Invoice >

Indented XML Files using C#, Formatting XML Files using C#, Create a Formatted XML file using C#, Writing XML Files using C#, C# Create XML Files, How to write XML Specification using C#

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment