Format an XML file so it looks nice in C#
When the computer processes an XML file, it doesn't care about formatting. It doesn't need indentation and new lines to make the file look nice. As long as the file is properly constructed, the file can be run all together in one long line as in:
<Employees><Employee><FirstName>Albert</FirstName><LastName>And
ers</LastName><EmployeeId>11111</EmployeeId></Employee><Employe
e><FirstName>Betty</FirstName><LastName>Beach</LastName><Employ
eeId>22222</EmployeeId></Employee><Employee><FirstName>Chuck</F
irstName><LastName>Cinder</LastName><EmployeeId>33333</Employee
Id></Employee></Employees> Formatting an XML document for human consumption isn't hard but it is confusing. The following code assumes you have created an XML document object as described in the example Use objects to make an XML document in C#. The following code formats and displays the object's XML.
ers</LastName><EmployeeId>11111</EmployeeId></Employee><Employe
e><FirstName>Betty</FirstName><LastName>Beach</LastName><Employ
eeId>22222</EmployeeId></Employee><Employee><FirstName>Chuck</F
irstName><LastName>Cinder</LastName><EmployeeId>33333</Employee
Id></Employee></Employees> Formatting an XML document for human consumption isn't hard but it is confusing. The following code assumes you have created an XML document object as described in the example Use objects to make an XML document in C#. The following code formats and displays the object's XML.
// Format the XML text.This code creates a StringWriter and an XmlTextWriter associated with it. It sets the XmlTextWriter's properties so it formats the XML code properly and then calls the XML document object's WriteTo method to write into the XmlTextWriter (which writes into the StringWriter). Finally it displays the text in the StringWriter. The following text shows the result.
StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;
xml_document.WriteTo(xml_text_writer);
// Display the result.
txtResult.Text = string_writer.ToString();
<Employees>
<Employee>
<FirstName>Albert</FirstName>
<LastName>Anders</LastName>
<EmployeeId>11111</EmployeeId>
</Employee>
<Employee>
<FirstName>Betty</FirstName>
<LastName>Beach</LastName>
<EmployeeId>22222</EmployeeId>
</Employee>
<Employee>
<FirstName>Chuck</FirstName>
<LastName>Cinder</LastName>
<EmployeeId>33333</EmployeeId>
</Employee>
</Employees>


Comments