Below program will allow you to write XML text into a stream and then save it into an xml file.
private void WriteToXML()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(Server.MapPath("Products.xml"), settings);
writer.WriteStartDocument();
writer.WriteComment("This is a generated XML File.");
writer.WriteStartElement("Product");
writer.WriteAttributeString("ID", "001");
writer.WriteAttributeString("Name", "Soap");
writer.WriteElementString("Price", "10.00");
writer.WriteStartElement("ProductDetails");
writer.WriteElementString("BrandName", "A Soap");
writer.WriteElementString("Manufacturer", "AB Company");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
Output:
<?xml version="1.0" encoding="utf-8" ?>
- <!-- This file is generated by the program.
-->
<Product ID="001" Name="Soap">
<Price>10.00</Price>
<OtherDetails>
<BrandName>X Soap</BrandName>
<Manufacturer>X Company</Manufacturer>
</OtherDetails>
</Product>
writer.WriteStartDocument()
Output:
<?xml version="1.0" encoding="utf-8" ?>
- <!-- This file is generated by the program.
-->
<Product ID="001" Name="Soap">
<Price>10.00</Price>
<OtherDetails>
<BrandName>X Soap</BrandName>
<Manufacturer>X Company</Manufacturer>
</OtherDetails>
</Product>
writer.WriteStartDocument()
Write the XML declaration. You can find on top of the XML document.
writer.WriteComment()
Write the XML comment.
writer.WriteStartElement()
Write the element of the XML.
writer.WriteAttributeString()
Add attributes to a element.
writer.WriteEndElement()
Closes the element.
writer.WriteEndDocument()
End writing the XML document.
Finally, we used the XmlWriter.Flush() method to clean the contents of the stream and the XmlWriter.Close() method to save the file and stop the program from using it
No comments:
Write comments