C# writing and xml file.
by brian on Jan.11, 2008, under Uncategorized
Writing xml files in c# is fairly painless and straight forward. I’ll use XmlTextWriter in the following example.
using System.Xml;
string name = "Joe";
int age = 23;
// create writer
XmlTextWriter writer =
new System.Xml.XmlTextWriter("test.xml", Encoding.UTF8);
writer.Indentation = 1;
writer.IndentChar = '\t';
// start the document
writer.WriteStartDocument(true);
// start an element
writer.WriteStartElement("templates");
writer.WriteAttributeString("version", "1.0.0.0");
// create a sub tag people
writer.WriteStartElement("people");
// create a sub tag person
writer.WriteStartElement("person");
// add the attribute age="23"
writer.WriteAttributeString("age",age.ToString());
// write out the full tag Joe
writer.WriteElementString("name",name);
// close out the person tag
writer.WriteEndElement();
// close out the people tag
writer.WriteEndElement();
// close the template tag
writer.WriteEndElement();
// end the document
writer.WriteEndDocument();
// close and write to file.
writer.Close();
Here is the resulting xml (formatting added)
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<templates version="1.0.0.0">
<people>
<person age="23">
<name>Joe</name>
</person>
</people>
</templates>
As I said writing xml is a piece of cake. Parsing on the other hand… I’ll keep you posted.
No comments for this entry yet...
Leave a Reply
You must be logged in to post a comment.
