How advanced DOM is used in XML

In this articles i am going to explain about advanced DOM in XML
  • 1911

Definition

The Document Object Model (DOM) is a language-independent and cross-platform convention for interacting and representing with objects in XHTML, HTML and XML documents. The DOM is a programming interface for XML and HTML documents. It defines the way a document can be manipulated and accessed .The DOM allows you to programmatically navigate the tree and add, delete and change any of its elements.

In an earlier chapter of this tutorial we introduced the XML DOM , and used the XML DOM getElementsByTagName() method to retrieve data from a DOM tree.

In this chapter we will describe some other commonly used XML DOM methods. In the examples, we have used the XML file books. xml, and a JavaScript function to load the XML file into an DOM object called xmlDoc.

Lets take an example of XML DOM Advanced

Get the Value of an Element

<html>
 <body>
 <script type="text/javascript">
 if (window.XMLHttpRequest)
 {
 xmlhttp=new XMLHttpRequest();
 }
 else
 {
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }
 xmlhttp.open("GET","abc.xml",false);
 xmlhttp.send();
 xmlDoc=xmlhttp.responseXML;
  txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
 document.write(txt);
 </script>
 </body>
 </html>

abc.xml file used in the examples:

This example retrieves the text value of the first <title> element

output

Clipboard01.jpg

Get the Value of an Attribute

<html>
<body>
<script type="text/javascript">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","abc.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");
document.write(txt);
</script>
</body>
</html>

This example retrieves the text value of the "lang" attribute of the first <title> element.

output

Clipboard02.jpg

Change the Value of an Element

<html>
<body>
<script type="text/javascript">
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","abc.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
x.nodeValue="Walking Tour";
x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
txt=x.nodeValue;
document.write(txt);
</script>
</body>
</html>

This example example changes the text value of the first <title> element:

output

Clipboard03.jpg

Further Readings

You may also read more about XML here

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2019 DotNetHeaven. All rights reserved.