Introduction to XML



CPAN 330 XML

Lecture #6: XML DOM

XML Document Object Model is a programming interface that defines how to access and manipulate an XML document. The DOM can be used with other kinds of documents like HTML,XHTL and CSS.

XML DOM can be used with any programming language. In this lecture we will use it with JavaScript, Java and .NET.

XML DOM can be used to create new XML documents, traverse through existing XML documents, add, modify, or even delete content from XML documents.

The DOM represents a tree view of the XML document. The documentElement is the top-level of the tree. This element has one or many childNodes that represent the branches of the tree.

The DOM is structures to model any XML document regardless of its structure. To develop an application that uses DOM to access XML document, we need an XML parser that is used to load the XML document into the DOM, and the DOM is used by any programming language as an intermediate layer to manipulate this document.

The DOM interfaces are divided into two categories: Fundamental and Extended. Your application needs to implement the fundamental interfaces regardless if you are working with XML or Non-XML documents. Extended interfaces must be implemented only if you are working with XML. You can extend the DOM interfaces to add more implementation. Following are the main DOM interfaces:

·        DOMImplementation: provides methods that are not specific to a particular document.

·        NodeList: provide properties for working with an ordered group of nodes.

·        Node: provides methods and properties that can be used with all types of nodes.

o       DocumentFragment: extends Node interface and is use to store s group of nodes temporarily.

o       Document: provides methods and properties that represent the entire XML document.

o       Element: provides methods and properties for working with elements.

o       Attr: provide properties for working with attributes.

o       CharacterData: provide methods and properties for working with character data.

• Text: provide extra methods for working with text.

• CDATASection: encapsulate CDATA section in XML documents.

• Comment: Encapsulate comments in XML documents.

o       DocumentType: provides attributes for working with XML document types.

o       Notation: provides properties for working with XML notations.

o       Entity: provides properties for working with parsed and unparsed entities.

o       EntityReference: encapsulate entity reference in XML documents.

o       ProcessingInstruction: provides attributes for working with P.I.

·        NamedNodeMap: represent an unordered group of nodes retrieved by name.

·        DOMException: provides properties for handling exceptions.

For more details about these interfaces , see Appendix A of the textbook.

 

 

DOM Tools: 

 

• MSXML :

 MSXML has support for DOM implementation. You can download the program from . We will use DOM with JavaScript that will be displayed using Internet Explorer.  

• Using DOM with JAVA:

 Java has support for DOM though a group of interfaces and packages. This enable us to use DOM in Java applications and applets.

 

•  Using DOM with .NET:

.NET  has support for DOM though a group of interfaces and classes . To develop .NET applications, you need to have the Microsoft .NET framework installed on your machine ( can be downloaded from ). Also you will need  a .NET Integrated Development Environment like Microsoft Visual Studio .NET.

 

Ex1: parse.html

This example will create an XML parser using XML DOM with JavaScript. If the page was not well formed. The script will report the errors. You can either load the XML document from a file or by typing the XML document in the provided text field.

function check()

{

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

xmlDoc.async="false";

var file=document.myform.myfile.value;

var text=document.myform.mytext.value;

// test if the user uploaded and XML file

if (file)

{

/*

If the XML document was not loaded from the file ,display a report.

The parser will report the errors one by one.

*/

if (!xmlDoc.load(file))

{

var str="Error line is :"+xmlDoc.parseError.line;

str=str+"\nError reason :"+xmlDoc.parseError.reason;

alert(str);

return;

}

}

// else test if the user pased an XML document into the text area

else if (text)

{

document.myform.myfile.value="";

/*

If the XML document was not loaded , display a report.

The parser will report the errors one by one.

*/

if (!xmlDoc.loadXML(text))

{

var str="Error line is :"+xmlDoc.parseError.line;

str=str+"\nError reason :"+xmlDoc.parseError.reason;

alert(str);

return;

}

}

alert("This document is Well-Formed");

}

Select an XML document to be validate

Or copy the XML document to the text area below

Following is an XML filed called invChoose.xml that will be tested using this script:

  

111A1C

23

23.5

shelves

111D4S

50

43.5

Computer table

222W3E

12

150.5

Set of Chairs

 

The following screenshot shows the output displayed using Internet Explorer.

 [pic]

 

 Ex2: traverse.html

 This example will traverse through the nodes of invChoose.xml using JavaScript:

 

function traverse()

{

var doc=document.parseForm.doc.value;

var xmlDoc = new ActiveXObject("MSXML.DOMDocument");

xmlDoc.async="false";

xmlDoc.load(doc);

/*

create an object represnting the child nodes of the root element. 

*/

x =xmlDoc.documentElement.childNodes;

var str="";

/*

return the text from all the child nodes of the root element including all thier child nodes.

*/

for (i=0;i< x.length;i++)

{

str+=(x.item(i).text+"\n");

}

document.parseForm.parsedDoc.value=str;

}

 

The following screenshot shows the output displayed using Internet Explorer:

[pic]

 

Ex3: createDoc.html

In this example we will use JavaScript to create an XML document using XML DOM:

 

 

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

/*

create a new XML element called inv

*/

var myNode=xmlDoc.createElement("inv");

/*

create a text node

*/

var myText=xmlDoc.createTextNode("inventory no 1");

/*

append inv element(node) to the new XML document

*/

xmlDoc.appendChild(myNode);

/*

append the text node to the inv node

*/

myNode.appendChild(myText);

/*

create an element called item

*/

var childNode=xmlDoc.createElement("item");

/*

append item node to inv node

*/

myNode.appendChild(childNode);

/*

create an attribute that is associated with item node

*/

childNode.setAttribute("id","1111");

/*

create a commnet node and append it at the end of the XML document

*/

var myComment=xmlDoc.createComment("This is a comment");

xmlDoc.appendChild(myComment);

// display the new document

alert( xmlDoc.xml);

// save the new document to the local drive

xmlDoc.save("c:/mine.xml");

 

Following is a screenshot of the output: 

[pic]

 

 

 Ex4: addelement.html

In this example we will add a new element called new at the end of the first item in invChoose.xml.

 

var xmlDoc = new ActiveXObject("MSXML.DOMDocument");

xmlDoc.async="false";

xmlDoc.load("invChoose.xml");

/* 

create an object representing the first child element(first item) in of inventory element

*/

var objMainNode=xmlDoc.documentElement.firstChild;

/*

create a new node called new

*/

var objNewNode=xmlDoc.createElement("new");

/*

append new node at the end of the first item in inventory document 

*/

objMainNode.appendChild(objNewNode);

alert( xmlDoc.xml);

Following is a screenshot of the output: 

[pic]

 

 Notice that we are making changes to the copy of the XML document  that is loaded into the computer memory. The original document stay intact. If you want to save the changes, you need to save the modified document to a physical  driver.

 

Ex5: addtext.html

 In this example we will add a new text node at the end of invChoose.xml:

 

 

var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

xmlDoc.async="false";

xmlDoc.load("invChoose.xml");

/*

create a text node

*/

var newtext=xmlDoc.createTextNode("Item 3 cancelled");

/*

add the new text node at the end of the inventory document

*/

xmlDoc.documentElement.appendChild(newtext);

alert( xmlDoc.xml);

Following is a screenshot of the output displayed using Internet Explorer:

[pic]

 

 Ex6: remove.html

In this example we will remove the quantity node of the first item from invChoose.xml document:

 

  

var xmlDoc = new ActiveXObject("MSXML.DOMDocument");

xmlDoc.async="false";

xmlDoc.load("invChoose.xml");

/*

create an object representing the first child node ( first item) of inventory document

*/

var oNode=xmlDoc.documentElement.childNodes[0];

/*

remove the second child node of the first item node

*/

oNode.removeChild(oNode.childNodes[1]);

/*

The following is an alternative way to do the same

oNode.removeChild(oNode.childNodes.item(1));

*/

alert( xmlDoc.xml);

Following is a screenshot of the output displayed using internet Explorer:

 

[pic]

 

 Ex7: Using DOM in a Java

download books.mdb 

We will create a Servlet that access a Microsoft access database called Books.mdb and create a new XML document based on book table using XML DOM:

 import java.io.*;

import java.sql.*;

import sun.jdbc.odbc.JdbcOdbcDriver;

import javax.xml.parsers.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.*;

import javax.xml.transform.stream.*;

import org.w3c.dom.*;

public class DOMDBtoXML

{

Connection con;

Document doc;

Element cat,cd,temp;

public void initDB()

{

try

{

JdbcOdbcDriver driver = new JdbcOdbcDriver();

String url = "jdbc:odbc:myData";

con = driver.connect(url, new java.util.Properties());

}

catch (Exception e)

{

}

}

public void doTheWork ()

{

try

{

Statement stmt = con.createStatement();

String sql = "";

/*

query book table

*/

sql = "select * from book";

ResultSet rs = stmt.executeQuery(sql);

/*

create a new XML document using XML DOM

*/

DocumentBuilderFactory f=DocumentBuilderFactory.newInstance();

DocumentBuilder b=f.newDocumentBuilder();

doc=b.newDocument();

/*

create a root element called bookstore

*/

cat=doc.createElement("bookstore");

/*

loop throug hhe result set and generate one XML record for each table record

*/

while (rs.next())

{

cd=doc.createElement("book");

temp=doc.createElement("title");

temp.appendChild(doc.createTextNode(rs.getString("title")));

cd.appendChild(temp);

temp=doc.createElement("author");

temp.appendChild(doc.createTextNode(rs.getString("author")));

cd.appendChild(temp);

temp=doc.createElement("publisher");

temp.appendChild(doc.createTextNode(rs.getString("publisher")));

cd.appendChild(temp);

temp=doc.createElement("price");

temp.appendChild(doc.createTextNode(rs.getString("price")));

cd.appendChild(temp);

temp=doc.createElement("edition");

temp.appendChild(doc.createTextNode(rs.getString("edition")));

cd.appendChild(temp);

cat.appendChild(cd);

}

}

catch (Exception e)

{

System.out.println(e.toString());

}

finally

{

/*

append the bookstore node to the new XML document

*/

doc.appendChild(cat);

try{

Source xmlSource=new DOMSource(doc);

/*

you can also provide an XSLT document to transfrom the new generated XML document.

*/

Source xslSource=new StreamSource("");

Result result=new StreamResult("c:/test.xml");

TransformerFactory tf=TransformerFactory.newInstance();

/*

pefrom the transformation. if you have an XMLT

pass the xsl source object as parameter to newTransformer

*/

Transformer transformer=tf.newTransformer();

/*

transform the XML document to the client

*/

transformer.transform(xmlSource,result);

}

catch(Exception e)

{

System.out.println(e.toString());

}

}

}

public static void main(String args[])

{

DOMDBtoXML obj= new DOMDBtoXML();

obj.initDB();

obj.doTheWork();

}

}

We will use JDBC to connect to Microsoft ODBC data source (Open Database Connectivity), which enables us to connect to a variety of databases. The driver used here is defined in JdbcOdbcDriver class in package sun.jdbc.odbc 

The first thing to do here is to register Microsoft Access database books.mdb as ODBC data source under Windows. The steps are summarized as follow:

·         From the Start menu, click Settings and then click Control Panel:

[pic]

Select ODBC Data Sources (32 Bit). (If you are using Windows 2000, you have to go first to Administrator Tools.) Double click it to display the ODBC Data Source Administrator dialog box:

[pic]

Make sure User DSN (Data Source Name) tab is selected and click the Add… button. Create new Data Source dialog appears:

[pic]

Select Microsoft Access Driver (*.mdb) and click finish to display the ODBC Microsoft Access Setup dialog:

[pic]

 

In the Data Source Name, type myData and under Database, click on the Select button to select the database. Locate the database file Books.mdb, select it and click OK button.

[pic]

 

Click the OK button on the ODBC Microsoft Access Setup dialog, and you will see your database source name has been added to the ODBC Data Source Administrator dialog. Then click the OK button to finish the database registry.

 

Now the database is ready to be used by the jdbc-odbc bridge driver in our Servlet.

 

Ex9: Using DOM in a .NET Application  

In this application we will open an XML document, manipulate it. The document  will be displayed before and after the changes for comparison reason only.  Since the DOM load the XML document into a memory area, the original document stays intact. to save the changes , the application provides a button  to save changes and exit the application. 

Create a new C#.NET application called DOMApp with the following GUI: 

 

[pic]

 

Following is a description of each control:

|Control Type |Control Name |Properties |

|Form |frmDOMApp |Text="DOM Example " |

|Button |btnXML |Text="Load XML File " |

|Text Box |txtXML |  |

|Button |btnDOM |Text="DOM Manipulation" |

|Button |btnSave |Text="Save Changes and Exit" |

|Label |lblBefore |Text="Before" |

|Label |lblAfter |Text="After" |

|TextBox |txtOutputBefore |Text="" |

| | |MultiLine=true |

| | |ScrollBar=vertical |

|TextBox |txtOutputAfter |Text="" |

| | |MultiLine=true |

| | |ScrollBar=vertical |

 

Following is the source code for the application. The bolded face code need to be added only. The rest should be generated by .NET IDE :

using System;

using System.Drawing;

using System.Collections;

using ponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Xml;

namespace DOMApp

{

///

/// Summary description for Form1.

///

public class frmDOMApp : System.Windows.Forms.Form

{

private System.Windows.Forms.Button btnXML;

private System.Windows.Forms.TextBox txtXMLFile;

///

private string XMLFileName;

private System.Windows.Forms.Label lblBefore;

private System.Windows.Forms.Label lblAfter;

private System.Windows.Forms.TextBox txtOutputBefore;

private System.Windows.Forms.TextBox txtOutputAfter;

private System.Windows.Forms.Button btnSave;

private System.Windows.Forms.Button btnDOM;

/// Required designer variable.

///

private ponentModel.Container components = null;

public frmDOMApp()

{

//

// Required for Windows Form Designer support

//

InitializeComponent();

//

// TODO: Add any constructor code after InitializeComponent call

//

}

///

/// Clean up any resources being used.

///

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null) 

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region Windows Form Designer generated code

///

/// Required method for Designer support - do not modify

/// the contents of this method with the code editor.

///

private void InitializeComponent()

{

this.btnXML = new System.Windows.Forms.Button();

this.txtXMLFile = new System.Windows.Forms.TextBox();

this.btnDOM = new System.Windows.Forms.Button();

this.txtOutputBefore = new System.Windows.Forms.TextBox();

this.txtOutputAfter = new System.Windows.Forms.TextBox();

this.lblBefore = new System.Windows.Forms.Label();

this.lblAfter = new System.Windows.Forms.Label();

this.btnSave = new System.Windows.Forms.Button();

this.SuspendLayout();

// 

// btnXML

// 

this.btnXML.Location = new System.Drawing.Point(72, 8);

this.btnXML.Name = "btnXML";

this.btnXML.Size = new System.Drawing.Size(136, 32);

this.btnXML.TabIndex = 0;

this.btnXML.Text = "Load XML File";

this.btnXML.Click += new System.EventHandler(this.btnXML_Click);

// 

// txtXMLFile

// 

this.txtXMLFile.Location = new System.Drawing.Point(216, 16);

this.txtXMLFile.Name = "txtXMLFile";

this.txtXMLFile.Size = new System.Drawing.Size(208, 20);

this.txtXMLFile.TabIndex = 1;

this.txtXMLFile.Text = "";

// 

// btnDOM

// 

this.btnDOM.Location = new System.Drawing.Point(72, 48);

this.btnDOM.Name = "btnDOM";

this.btnDOM.Size = new System.Drawing.Size(136, 32);

this.btnDOM.TabIndex = 2;

this.btnDOM.Text = "DOM Manipulation";

this.btnDOM.Click += new System.EventHandler(this.btnDOM_Click);

// 

// txtOutputBefore

// 

this.txtOutputBefore.Location = new System.Drawing.Point(16, 152);

this.txtOutputBefore.Multiline = true;

this.txtOutputBefore.Name = "txtOutputBefore";

this.txtOutputBefore.Size = new System.Drawing.Size(240, 160);

this.txtOutputBefore.TabIndex = 3;

this.txtOutputBefore.Text = "";

// 

// txtOutputAfter

// 

this.txtOutputAfter.Location = new System.Drawing.Point(288, 152);

this.txtOutputAfter.Multiline = true;

this.txtOutputAfter.Name = "txtOutputAfter";

this.txtOutputAfter.Size = new System.Drawing.Size(240, 160);

this.txtOutputAfter.TabIndex = 4;

this.txtOutputAfter.Text = "";

// 

// lblBefore

// 

this.lblBefore.Location = new System.Drawing.Point(32, 120);

this.lblBefore.Name = "lblBefore";

this.lblBefore.Size = new System.Drawing.Size(88, 16);

this.lblBefore.TabIndex = 5;

this.lblBefore.Text = "Before";

// 

// lblAfter

// 

this.lblAfter.Location = new System.Drawing.Point(296, 120);

this.lblAfter.Name = "lblAfter";

this.lblAfter.Size = new System.Drawing.Size(88, 16);

this.lblAfter.TabIndex = 6;

this.lblAfter.Text = "After";

// 

// btnSave

// 

this.btnSave.Location = new System.Drawing.Point(224, 48);

this.btnSave.Name = "btnSave";

this.btnSave.Size = new System.Drawing.Size(136, 32);

this.btnSave.TabIndex = 7;

this.btnSave.Text = "Save Changes and Exit";

this.btnSave.Click += new System.EventHandler(this.btnSave_Click);

// 

// frmDOMApp

// 

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

this.ClientSize = new System.Drawing.Size(536, 357);

this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.btnSave,

this.lblAfter,

this.lblBefore,

this.txtOutputAfter,

this.txtOutputBefore,

this.btnDOM,

this.txtXMLFile,

this.btnXML});

this.Name = "frmDOMApp";

this.Text = "DOM Example";

this.Load += new System.EventHandler(this.frmDOMApp_Load);

this.ResumeLayout(false);

}

#endregion

///

/// The main entry point for the application.

///

[STAThread]

static void Main() 

{

Application.Run(new frmDOMApp());

}

private void frmDOMApp_Load(object sender, System.EventArgs e)

{

}

private void btnXML_Click(object sender, System.EventArgs e)

{

try

{

OpenFileDialog of=new OpenFileDialog();

of.Filter="All Files(*.*)|*.*";

DialogResult dr=of.ShowDialog();

if (dr==DialogResult.Cancel)

MessageBox.Show ("No file has been selected","Error",MessageBoxButtons.OK);

else

{

XMLFileName=of.FileName;

if (XMLFileName=="" || XMLFileName==null)

MessageBox.Show ("Invalid file name","Error",MessageBoxButtons.OK);

else

{

txtXMLFile.Text=XMLFileName;

}

}

}

catch(IOException ioe)

{

txtOutputBefore.Text="IOException "+ioe.ToString();

}

}

private void btnDOM_Click(object sender, System.EventArgs e)

{

try

{

// create an instance of XmlTextReader

XmlTextReader tr=new XmlTextReader(XMLFileName);

// create an XmlDocument instance 

XmlDocument doc=new XmlDocument();

// load the entire XML document into a memory representation of DOM tree

doc.Load(tr);

// output the xml document to the first text box

StringWriter rr=new StringWriter();

XmlTextWriter xtw=new XmlTextWriter(rr);

doc.WriteTo(xtw);

txtOutputBefore.Text=rr.ToString();

// get the DocumentElement

XmlElement element=doc.DocumentElement;

// create new child element called Test

XmlElement newElement= doc.CreateElement("Test");

// set an attribute called no for Test element

newElement.SetAttribute("no",null,"abc");

// create a text node and append it to Test element

XmlText textNode=doc.CreateTextNode("This is an example of adding an element");

newElement.AppendChild(textNode);

// insert the Test element before the first chid element of the DocumentEllement 

element.InsertBefore ( newElement,element.FirstChild);

/* create an element called childTest and append it 

to Test element

*/

XmlElement childElement=doc.CreateElement("ChildTest");

newElement.AppendChild(childElement);

/* create the elements test1, test2,test3 and test4 with 

* corresponding attributes mark1, mark2,mark3 and mark4.

* The values for the attributes are assigned randomly.

* */

Random r = new Random();

for(int i=0;i ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download