Usually, we save data in databases. However, if we want to make the data more portable, we can store the data in an XML file.
Create and Save an XML File
Storing data in XML files is useful if the data is to be sent to applications on non-Windows platforms. Remember that XML is portable across all platforms and the data will not need to be converted!First we will learn how to create and save an XML file. The XML file below will be named "test.xml" and will be stored in the c directory on the server. We will use ASP and Microsoft's XMLDOM object to create and save the XML file:
<% 'Create an XML document 'Create a root element and append it to the document 'Create and append child elements 'Add an XML processing instruction 'Save the XML file to the c directory |
If you open the saved XML file it will look something like this ("test.xml"):
|
Real Form Example
Now, we will look at a real HTML form example.
We will first look at the HTML form that will be used in this example: The HTML form below asks for the user's name, country, and e-mail address. This information will then be written to an XML file for storage.
"customers.htm":
|
The action for the HTML form above is set to "saveForm.asp". The "saveForm.asp" file is an ASP page that will loop through the form fields and store their values in an XML file:
<% 'Do not stop if an error occurs Set xmlDoc = server.CreateObject("Microsoft.XMLDOM") 'Create a root element and append it to the document 'Loop through the form collection 'Add an XML processing instruction 'Save the XML file 'Release all object references 'Test to see if an error occurred |
Note: If the XML file name specified already exists, it will be overwritten!
The XML file that will be produced by the code above will look something like this ("Customer.xml"):
|