Creating XML Trees with the XmlTextWriter and XmlDocument Objects - Spending Time in the Library
(Page 2 of 7 )
The XmlTextWriter object can best be considered as a counterpart to the XmlTextReader object, allowing you to perform the reverse function. The next example shows you how:
<%@ Page Language="C#" Debug="true" %>
<%@ import namespace="System.Xml"%>
<html>
<head>
<script runat="server">
void Page_Load() {
// initialize a XmlTextWriter object
XmlTextWriter objXmlWriter = null;
// location to the XML file to write
String strXmlFile = "E:/Inetpub/wwwroot/xml/library.xml";
// start the "try" block
try {
objXmlWriter = new XmlTextWriter (strXmlFile , null);
// start writing the XML document
objXmlWriter.WriteStartDocument(false);
// start with the root element
objXmlWriter.WriteStartElement("library");
// first child element
objXmlWriter.WriteStartElement("book", null);
// add an attribute
objXmlWriter.WriteAttributeString("bkid","MFRE001");
// some text
objXmlWriter.WriteElementString("title", "XML and PHP");
// back to the root element
// closing each element written above
// one at a time
objXmlWriter.WriteEndElement();
objXmlWriter.WriteEndElement();
// flush the object and write the
// XML data to the file
objXmlWriter.Flush();
} catch (XmlException e) {
output.Text = "An XML Exception occurred: " + e.Message;
} catch (Exception e) {
output.Text = "A General Exception occurred: " + e.Message;
} finally {
// Close the XMLWriter object
if(objXmlWriter != null) {
objXmlWriter.Close();
}
}
}
</script>
</head>
<body>
<asp:label id="output" runat="server" text="It's all done!" />
</body>
</html>
Run this example in your browser, and you might see something like this:
A General Exception occurred: Access to the path
"E:/Inetpub/wwwroot/xml/library.xml" is denied.
Don't despair! This is just a matter of giving appropriate permissions on the target directory to the user. But which user?
According to the official ASP.NET documentation, the "ASP.NET V1 RTM now runs using a less privileged Windows account, registered as the ASPNET account on a local machine" (http://www.asp.net/security.aspx?tabindex=0&tabid=1).
So, all this means that you need to locate the "ASPNET" user in your user management control panel and give the corresponding user account permission to write to the target directory. Once that's done, run the example again, and you will now see a more cheerful message:
It's all done.
In reality, the action takes place elsewhere.
Navigate to the location specified in the script and look for a file called library.xml. This is what it should look like.
<?xml version="1.0" standalone="no"? ><library><book
bkid="MFRE001"><title>XML and PHP</title></book></library>
At first glance, this is very unattractive to the naked eye. I will show you later how this can be formatted to look a little nicer. First, though, it's time for a quick anatomy lesson on the code above.
Next: Breaking It Down >>
More XML Articles
More By Harish Kamath (c) Melonfire