Creating XML Trees with the XmlTextWriter and XmlDocument Objects - Walking the DOM
(Page 5 of 7 )
Now, you've seen in previous issues of this column how the XmlDocument object can read an XML file, build a tree to represent the structures found within it, and expose object methods and properties to manipulate them. What you have not yet seen is that this same object can be used to build a complete XML DOM tree in memory and then write it to a file. Take a look at the next example, which demonstrates this:
<%@ Page Language="C#" Debug="true" %>
<%@ import namespace="System.Xml"%>
<html>
<head>
<script runat="server">
XmlElement MyElement(XmlDocument objXmlDocument, String strElementName,
String strElementText) {
XmlElement objElement =
objXmlDocument.CreateElement(strElementName,null);
objElement.AppendChild(objXmlDocument.CreateTextNode(strElementText));
return objElement;
}
void Page_Load() {
// initialize a XmlTextWriter object
XmlDocument objXmlDocument = null;
// path to the XML file to write
String strXmlFile = "E:/Inetpub/wwwroot/xml/library.xml";
// start the "try" block
try {
// instantiate an XmlDocument object
objXmlDocument = new XmlDocument();
// create an XmlDeclaration object
// and append it to XmlDocument object
XmlDeclaration objXmlDec = objXmlDocument.CreateXmlDeclaration("1.0", null, "no");
objXmlDocument.AppendChild(objXmlDec);
// create a root level element
XmlElement objRootElement =
objXmlDocument.CreateElement("library",null);
// create first level element
XmlElement objElementLeveOne =
objXmlDocument.CreateElement("book",null);
// append elements at second level to the first level element
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"title","XML and PHP"));
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"author","Vikram Vaswani"));
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"description","Learn to manage your XML data with PHP"));
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"price","24.95"));
// append first level to the root element
objRootElement.AppendChild(objElementLeveOne);
// append the entire hierarchy built above to the
XMLDocument object
objXmlDocument.AppendChild(objRootElement);
// save the file
objXmlDocument.Save(strXmlFile);
} 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 XmlDocument object
if(objXmlDocument != null) {
objXmlDocument = null;
}
}
}
</script>
</head>
<body>
<asp:label id="output" runat="server" text="It's all done." />
</body>
</html>
Here's what the resulting XML file should look like.
<?xml version="1.0" standalone="no"? >
<library>
<book bkid="MFRE001">
<title>XML and PHP</title>
<author>Vikram Vaswani</author>
<description>Learn to manage your XML data with PHP</description>
<price>24.95</price>
</book>
</library>
Just the way I like it.
Let's see how our ASP.NET script generated this output:
1. As usual, the first step is to import the .NET libraries for the XML parser:
<%@ import namespace="System.Xml"%>
2. Within the Page_Load() function, I have defined some variables and objects -- a local instance of the XmlDocument object and a string variable to store the location of the XML file. Note that here too, you have to give an absolute file path -- no URLs allowed!
<%
// initialize a XmlTextWriter object
XmlDocument objXmlDocument = null;
// path to the XML file to write
String strXmlFile = "E:/Inetpub/wwwroot/xml/library.xml";
%>
3. The code snippet starts with the instantiation of the XmlDocument object that will allow me to build the XML tree in memory. I begin the process by creating an XmlDeclaration object, representing the XML prologue at the top of the document.
The XmlDocument object comes with an AppendChild() method (I will be using this method repeatedly) to attach the object (in this case, the XmlDeclaration object) passed as input to the DOM tree.
<%
// instantiate an XmlDocument object
objXmlDocument = new XmlDocument();
// create an XmlDeclaration object
// and append it to XmlDocument object
XmlDeclaration objXmlDec = objXmlDocument.CreateXmlDeclaration("1.0", null, "no");
objXmlDocument.AppendChild(objXmlDec);
%>
4. You already know that the DOM revolves around a tree structure that is made up of hierarchical layers of nodes sharing a parent-child relationship between themselves. Building such a tree in memory requires a similar approach -- first create an XmlElement object using the CreateElement() method of the XmlDocument object, then attach it to its parent by using the AppendChild() method. This process is demonstrated below:
<%
// create a root level element
XmlElement objRootElement = objXmlDocument.CreateElement("library",null);
// create first level element
XmlElement objElementLeveOne =
objXmlDocument.CreateElement("book",null);
%>
5. Why only use AppendChild() on objects? The XmlElement object comes with a similar method that allows you to easily attach children to an existing element. I've used this knowledge to add a second level to my DOM tree, as below:
<%
// append elements at second level to first level element
objElementLeveOne.AppendChild(MyElement(objXmlDocument, "title","XML and PHP"));
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"author","Vikram Vaswani"));
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"description","Learn to manage your XML data with PHP"));
objElementLeveOne.AppendChild(MyElement(objXmlDocument,
"price","24.95"));
%>
Since I plan to add four children to the <book> element (and you might want to add many more in real life), it makes sense to write a simple function that will do the hard work of creating an element and its data. That's where my MyElement() function comes in. Take a closer look at this to see how it works.
<%
XmlElement MyElement(XmlDocument objXmlDocument, String strElementName, String strElementText) {
XmlElement objElement = objXmlDocument.CreateElement(strElementName,null);
objElement.AppendChild(objXmlDocument.CreateTextNode(strElementText));
return objElement;
}
%>
This custom MyElement() function takes three parameters -– the XmlDocument object, the name of the element to be created and the data for that element. The function first uses the CreateElement() method to create an XmlElement object, and the CreateTextNode() method to insert a text node at this point. Once its job is complete, the function returns the XmlElement object to the main Page_Load() function and the script continues executing - except, of course, that the objElementLeveOne object is now populated with four new child elements.
6. In this manner, I keep append objects to their respective parents in a recursive manner, until the root element is reached. The Save() method is now used to write the entire tree to a flat-file, as shown below:
<%
// append first level to the root element
objRootElement.AppendChild(objElementLeveOne);
// append the entire hierarchy built above to our XMLDocument object
objXmlDocument.AppendChild(objRootElement);
// save to a file
objXmlDocument.Save(strXmlFile);
%>
The mandatory try-catch blocks trap unforeseen errors, and free up memory associated with the objects created in the script.
Next: Adding More >>
More XML Articles
More By Harish Kamath (c) Melonfire