I have seen that at times we need to generate XML using code. This is in contrast to web services, where in XML is generated by the compiler. In this post I would like to give some pointers about creating XML files using C# - the "XmlWriter" class. Consider the following piece of code:
XmlWriter xml = XmlWriter.Create(@"c:\file.xml");
This would instantiate a XML writer and you could use various commands like xml.WriteStartElement(...), xml. WriteValue(..), xml.WriteEndElement() to construct the XML file dynamically. But there is a problem w/ this. A file created w/ such an instance of XmlWriter (xml) would like this:
<?xml version="1.0" encoding="utf-8"?><Users><User><Name>user1</Name></User><User><Name>user2</Name></User><User><Name>user3</Name></User></Users>
But, we may expect the XML file to have some line breaks, indentation to make it readable to others (though XML is not meant for that! ;) ). For this we need to apply some XML writer settings using the "XmlWriterSettings" class as shown below:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;
Now the XmlWriter would be instantiated as:
XmlWriter xml = XmlWriter.Create(path, xmlWriterSettings);
With this the XML generated would be indented, with line breaks as appropriate! Check out the final output after the addition settings:
<?xml version="1.0" encoding="utf-8"?>
<Users>
<User>
<Name>user1</Name>
</User>
<User>
<Name>user2</Name>
</User>
<User>
<Name>user3</Name>
</User>
</Users>
Check out the code in full:
void Main()
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;
XmlWriter xml = XmlWriter.Create(@"C:\file.xml", xmlWriterSettings);
xml.WriteStartElement("Users");
foreach (string client in new string[] {"user1","user2","user3"})
{
xml.WriteStartElement("User");
xml.WriteStartElement("Name");
xml.WriteValue(client);
xml.WriteEndElement();
xml.WriteEndElement();
}
xml.WriteEndElement();
xml.Close();
}