Solution 1:
If you want to Write a XML string using XmlWriter, you can use below code.
Add below namespace references to the project.
using System.Xml;
using System.IO;
using System.Text;
The XmlWriter and XmlTextWriter classes are defined in the System.XML namespace.
StringBuilder strbuilder = new StringBuilder();
using (XmlTextWriter xmltxtwriter = new XmlTextWriter(stringWriter))
{
xmltxtwriter.Formatting = Formatting.Indented;
// Add elements to the string
xmltxtwriter.WriteStartElement("Employee");
xmltxtwriter.WriteAttributeString("Contract Year", "2010");
xmltxtwriter.WriteStartElement("Name");
xmltxtwriter.WriteString("Employee Name");
xmltxtwriter.WriteEndElement();
xmltxtwriter.WriteStartElement("UserName");
xmltxtwriter.WriteString("User Name");
xmltxtwriter.WriteEndElement();
xmltxtwriter.WriteStartElement("StartDate");
xmltxtwriter.WriteString("Start Date of Contract");
xmltxtwriter.WriteEndElement();
xmltxtwriter.WriteStartElement("EndDate");
xmltxtwriter.WriteString("End Date of Contract");
xmltxtwriter.WriteEndElement();
xmltxtwriter.Close();
}
Console.WriteLine(strbuilder.ToString());
Console.Read();
Solution 2:
If you want to Write to XML File using XmlWriter, you can use below code.
Add below namespace reference to the project.
using System.Xml;
The XmlWriter and XmlTextWriter classes are defined in the System.XML namespace.
// Creates an XML file, if it doesn’t exist
using (XmlTextWriter writer= new XmlTextWriter("C:\\Test.xml",null ))
{
// Starts a new document
writer.WriteStartDocument();
// Add elements to the file
writer.WriteStartElement("Employee");
writer.WriteAttributeString("Contract Year", "2010");
writer.WriteStartElement("Name");
writer.WriteString("Employee Name");
writer.WriteEndElement();
writer.WriteStartElement("UserName");
writer.WriteString("User Name");
writer.WriteEndElement();
writer.WriteStartElement("StartDate");
writer.WriteString("Start Date of Contract");
writer.WriteEndElement();
writer.WriteStartElement("EndDate");
writer.WriteString("End Date of Contract");
writer.WriteEndElement();
// Ends the document
writer.WriteEndDocument();
writer.Close();
}
No comments:
Post a Comment