by the3factory
3/3/2008 10:41:00 PM
Employees.xml
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<employees>
<employee id="1">
<name>
<firstName>Nancy</firstName>
<lastName>lastName</lastName>
</name>
<city>Seattle</city>
<state>WA</state>
<zipCode>98122</zipCode>
</employee>
</employees>
Demo:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Xml" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
string xmlFilePath = "Employees.xml";
try
{
using (XmlWriter writer = XmlWriter.Create(xmlFilePath))
{
//Start writing the XML document
writer.WriteStartDocument(false);
writer.WriteComment("This XML file represents the details of an employee");
//Start with the root element
writer.WriteStartElement("employees");
writer.WriteStartElement("employee");
writer.WriteAttributeString("id", "2");
writer.WriteStartElement("name");
writer.WriteElementString("firstName", "Nancy");
writer.WriteElementString("lastName", "lastName");
writer.WriteEndElement();
writer.WriteElementString("city", "Seattle");
writer.WriteElementString("state", "WA");
writer.WriteElementString("zipCode", "98122");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
//flush the object and write the XML data to the file
writer.Flush();
lblResult.Text = "File is written successfully";
}
}
catch (Exception ex)
{
lblResult.Text = "An Exception occurred: " + ex.Message;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Writing XML File</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:label id="lblResult" runat="server" />
</div>
</form>
</body>
</html>