XML DOM
DOM stands for "Document Object Model" which defines a standard way
for accessing and manipulating documents. So the XML DOM (XML Document Object
Model) defines a standard way for accessing and manipulating XML documents.
With DOM, all elements can be accessed, modified, deleted, and created.
In the examples below we use the following DOM reference to get the text from
the <to> element:
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue
In the script above, "xmlDoc" is the XML document created
by the parser; "getElementsByTagName("to")[0]"
is the first <to> element; "childNodes[0]" is the first
child of the <to> element (the text node); and "nodeValue"
is the value of the node (the text itself).
Let's see a Cross browser example. The following code loads an XML document
("email.xml") into the XML parser:
<html>
<head>
<script type="text/Javascript">
function parseXML()
{
text="<note>";
text=text+"<to>John</to>";
text=text+"<from>Michael</from>";
text=text+"<subject>Hi</subject>";
text=text+"<body>Hello my friend!</body>";
text=text+"</note>";
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
catch(e)
{
try // Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
catch(e)
{
alert(e.message);
return;
}
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
}
</script>
</head>
<body onload="parseXML()">
<h1>Email</h1>
<p><b>To:</b> <span id="to"></span><br
/>
<b>From:</b> <span id="from"></span><br
/>
<b>Message:</b> <span id="message"></span>
</p>
</body>
</html>
Output:
Email
To: John
From: Michael
Message: Hello my friend!
|