I have seen that at times, we need to generate XML using code. This is in contrast to web services, wherein XML is generated by the compiler. In this post, I would like to give some pointers about creating XML files using C# - the "
" class. Consider the following piece of code:
XmlWriter xml = XmlWriter.Create(@"c:\file.xml");
This would instantiate an XML writer and you could use various commands like
to construct the XML file dynamically. But there is a problem with this. A file created with such an instance of
(XML) would look like this:
But, we may expect the XML file to have some line breaks, indentation to make it readable to others. For this, we need to apply some XML writer settings using the "
" class as shown below:
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.NewLineOnAttributes = true;
xmlWriterSettings.Indent = true;
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 additional settings: