XML
  Home arrow XML arrow Page 5 - Creating XML Trees with the XmlTextWriter ...
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Mobile Linux 
App Generation ROI 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

Creating XML Trees with the XmlTextWriter and XmlDocument Objects
By: Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 26
    2004-04-21

    Table of Contents:
  • Creating XML Trees with the XmlTextWriter and XmlDocument Objects
  • Spending Time in the Library
  • Breaking It Down
  • The Real Thing
  • Walking the DOM
  • Adding More
  • Linking Out

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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 objXmlDocumentString 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 objXmlDocumentString strElementNameString 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.

    More XML Articles
    More By Harish Kamath (c) Melonfire


     

    XML ARTICLES

    - More on Triggers and Styles and Control Temp...
    - Looking at Triggers with Styles and Control ...
    - A Closer Look at Styles and Control Templates
    - Styles and Control Templates
    - Properties and More in XAML
    - Elements and Attributes in XAML
    - XAML in a Nutshell
    - Importing XML Files into Access 2007
    - Using MSXML3.0 with VB 6.0
    - MSXML, concluded
    - MSXML, continued
    - MSXML Tutorial
    - Generating XML Schema Dynamically Using VB.N...
    - XSL Transformations using ASP.NET
    - Applying XSLT to XML Using ASP.NET





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway
    Stay green...Green IT