Advertise Here
XML Files - Extensible Markup Language Tutorials for Developers - Web01
Extensible Markup Language

Search XML Files:

DEVELOPER CHANNEL
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

Find a Web Host With:
CGI Capabilities
Active Server Pages
Windows Hosting
Unix Hosting
Dedicated Servers
     
 Advanced Search
 Be a Commerce Partner















IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

Appending to XML with ASP

By
Michael Qualls

Introduction

This example assumes that you are familiar with ASP, XML and HTML 4.0.

Append new "records" to your XML files

This article is the third in a series of articles on manipulating XML data with ASP. Before proceding with this article, I recommend that you read Saving HTML Form Data to XML and Editing XML with XSL and ASP.

The example in this article is very similar to the example on Saving HTML Form Data to XML. However, instead of creating a new file each time that the form is submitted, we will check to see if the file already exists, and if it does, we will append to it. Using this type of technique, we are creating a data construct similar to a data base table.

In the previous articles, I already demonstrated how to instantiate and use the XMLDOM Object. So, lets go ahead and dive right into the example.

Example: Appending to XML with ASP:

The first thing that we need to look at is the HTML form that we will use to add the new "record". This is the same form that was used in the Saving HTML Form Data to XML Example (The name of the HTML file has been changed, but the code is the same).

AddContact.html:


<html>
<head>
 <title>
  Contact Information
 </title>
</head>
<body>
 <form action="processAdd.asp" method="post">
  <h3>Enter your contact information</h3>
  First Name: <input type="text" id="firstName" name="firstName"><br>
  Last Name: <input type="text" id="lastName" name="lastName"><br>
  Address #1: <input type="text" id="address1" name="address1"><br>
  Address #2: <input type="text" id="address2" name="address2"><br>
  Phone Number: <input type="text" id="phone" name="phone"><br>
  E-Mail: <input type="text" id="email" name="email"><br>
  <input type="submit" id="btnSub" name="btnSub" value="Submit"><br>
 </form>
</body>
</html>

The action for this HTML form is set to processAdd.asp. This ASP page will call a function which tests to see if the XML file, rolodex.xml, exists. If it does exist, it will append the new entry to the file. If the file does not exist, the file will be created.

processAdd.asp:


<%

'--------------------------------------------------------------------
'The "addNewContacttoXML" Function accepts two parameters.
'strXMLFilePath - The physical path where the XML file will be saved.
'strFileName - The name of the XML file that will be saved.
'--------------------------------------------------------------------

Function addNewContacttoXML(strXMLFilePath, strFileName)

 'Declare local variables.
 Dim objDom
 Dim objRoot
 Dim objRecord
 Dim objField
 Dim objFieldValue
 Dim objattID
 Dim objattTabOrder
 Dim objPI
 Dim blnFileExists
 Dim x


 'Instantiate the Microsoft XMLDOM.
 Set objDom = server.CreateObject("Microsoft.XMLDOM")
 objDom.preserveWhiteSpace = True


 'Call the Load Method of the XMLDOM Object. The Load Method has a
 'boolean return value indicating whether or not the file could be
 'loaded. If the file exists and loads it will return true, otherwise,
 'it will return false.
 blnFileExists = objDom.Load(strXMLFilePath & "\" & strFileName)


 'Test to see if the file loaded successfully.
 If blnFileExists = True Then

  'If the file loaded set the objRoot Object equal to the root element
  'of the XML document.
  Set objRoot = objDom.documentElement
 Else

  'Create your root element and append it to the XML document.
  Set objRoot = objDom.createElement("rolodex")
  objDom.appendChild objRoot
 End If


 'Create the new container element for the new record.
 Set objRecord = objDom.createElement("contact")
 objRoot.appendChild objRecord


 'Iterate through the Form Collection of the Request Object.
 For x = 1 To Request.Form.Count

  'Check to see if "btn" is in the name of the form element. If it is,
  'then it is a button and we do not want to add it to the XML
  'document".
  If instr(1,Request.Form.Key(x),"btn") = 0 Then

   'Create an element, "field".
   Set objField = objDom.createElement("field")

   'Create an attribute, "id".
   Set objattID = objDom.createAttribute("id")

   'Set the value of the id attribute equal the the name of the current
   'form field.
   objattID.Text = Request.Form.Key(x)

   'The setAttributeNode method will append the id attribute to the
   'field element.
   objField.setAttributeNode objattID

   'Create another attribute, "taborder". This just orders the
   'elements.
   Set objattTabOrder = objDom.createAttribute("taborder")

   'Set the value of the taborder attribute.
   objattTabOrder.Text = x

   'Append the taborder attribute to the field element.
   objField.setAttributeNode objattTabOrder

   'Create a new element, "field_value".
   Set objFieldValue = objDom.createElement("field_value")

   'Set the value of the field_value element equal to the value of the
   'current field in the Form Collection.
   objFieldValue.Text = Request.Form(x)

   'Append the field element as a child of the new record container
   'element, contact.
   objRecord.appendChild objField

   'Append the field_value element as a child of the field element.
   objField.appendChild objFieldValue
  End If
 Next 


 'Check once again to see if the file loaded successfully. If it did
 'not, that means we are creating a new document and need to be sure to
 'insert the XML processing instruction.
 If blnFileExists = False then

  'Create the xml processing instruction.
  Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")

  'Append the processing instruction to the XML document.
  objDom.insertBefore objPI, objDom.childNodes(0)
 End If


 'Save the XML document.
 objDom.save strXMLFilePath & "\" & strFileName


 'Release all of your object references.
 Set objDom = Nothing
 Set objRoot = Nothing
 Set objRecord = Nothing
 Set objField = Nothing
 Set objFieldValue = Nothing
 Set objattID = Nothing
 Set objattTabOrder = Nothing
 Set objPI = Nothing
End Function


'Do not break on an error.
On Error Resume Next


'Call the addNewContacttoXML function, passing in the physical path to
'save the file to and the name that you wish to use for the file.
addNewContacttoXML "c:","rolodex.xml"


'Test to see if an error occurred, if so, let the user know.
'Otherwise, tell the user that the operation was successful.
If err.number <> 0 then
 Response.write("Errors occurred while saving your form submission.")
Else
 Response.write("Your form submission has been saved.")
End If
%>

If you have read the Saving HTML Form Data to XML Article you will notice that the code to append the HTML data to the XML file is almost identical to the code used to save HTML data to a new file. There are two main differences in the addNewContacttoXML Function used in this example and the ConvertFormtoXML Function used in the Saving HTML Form Data to XML example. Lets take a look at those differences:


 'Call the Load Method of the XMLDOM Object. The Load Method has a
 'boolean return value indicating whether or not the file could be
 'loaded. If the file exists and loads it will return true, otherwise,
 'it will return false.
 blnFileExists = objDom.Load(strXMLFilePath & "\" & strFileName)


 'Test to see if the file loaded successfully.
 If blnFileExists = True Then

  'If the file loaded set the objRoot Object equal to the root element
  'of the XML document.
  Set objRoot = objDom.documentElement
 Else

  'Create your root element and append it to the XML document.
  Set objRoot = objDom.createElement("contact")
  objDom.appendChild objRoot
 End If

This section of code is from the addNewContacttoXML Function. Since we are not creating a new file each time we save a contact now, we need to call the Load Function of the XMLDOM Object and attempt to load the file. If we are able to load the file, we obtain a reference to the root element of the XML document. If the file does not load, we assume that it does not exist and create reference to a new root element and append it to the XML Document.

The other main difference is when we test a second time to see if the file was successfully loaded so that we know whether or not we need to add a processing instruction. If the file exists, we do not need a processing instruction. However, if a new file is being created, a processing instruction must be added.


 'Check once again to see if the file loaded successfully. If it did
 'not, that means we are creating a new document and need to be sure to
 'insert the XML processing instruction.
 If blnFileExists = False then

  'Create the xml processing instruction.
  Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")

  'Append the processing instruction to the XML document.
  objDom.insertBefore objPI, objDom.childNodes(0)
 End If

Other than these two differences, however, you will notice that the code to save data to a new file is virtually the same as the code to append a new record to an existing file. We create a new container element, contact, as a child of the root element, rolodex, to hold the data for each new record added. The code then iterates through the Form Collection of the Request Object creating the appropriate XML nodes and setting the nodes' values equal to the current Form Field.

As always, I recommend that you copy this code to your development server and give it a run. I hope that this example is helpful and adds to your coding efforts!

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
New at Developer.com/Voice/
- Designing an Interactive Voice Response System Using VoiceXML and CCXML
- Nominations for Developer.com Product of the Year Begin October 15
- Speech Authentication Strategies, Risk Mitigation, and Business Metrics
- Implementing Extension Methods in VB.NET
 DevX XML Content 
- Processing Linked Web Data with XSLT
- Using StAX to Clone an XML Document
- Ten Pitfalls of Enterprise Ontology Management
- WPF Meets the iPhone
- The Easiest and Most Efficient Way to Modify XML Documents

Jump to : Top Of Page or HOME




JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES