XML Parser

To access and manipulate XML, a built-in XML parser is present in all major browsers.

XML Parser:

To define the properties and methods for accessing and editing XML, the XML DOM (Document Object Model) is created. An XML document must be loaded into an XML DOM object, before accessing it. To convert text into an XML DOM object a built-in XML parser is present in all modern browsers.

Parsing a Text String:

Example:





Output:

Explanation:

In the above example, we are parsing a text string into an XML DOM object. We are then extracting the info from it with JavaScript.

  • In the below lines of code, we are defining a text string:
    text = "" +
    "Meeting on Monday Morning at 9 AM" +
    "Sapna" +
    "Tom" +
    "";
    
  • In the below lines of code, we are creating an XML DOM parser:
    parser = new DOMParser();
  • In the below lines of code, a new XML DOM object is created by the parser using the text string:
    xmlDoc = parser.parseFromString(text,"text/xml");

Old Versions of Internet Explorer:

The DOMParser object is not supported by the old versions of Internet Explorer (IE5, IE6, IE7, IE8). We need to first determine if the browser supports the DOMParser object, to handle older versions of Internet Explorer, otherwise, we need to create an ActiveXObject.

Example:





Output:

The XMLHttpRequest Object:

A built-in XML Parser is present in an XMLHttpRequest Object. The response is returned as a string, by the responseText property. The response is returned as an XML DOM object, by the responseXML property. The responseXML property can thus be used to use the response as an XML DOM object.

Example:




Music Collection

Output:

Explanation:

In the above example, we are requesting the cd_catalog.xml file. We are then using the response as an XML DOM object.

Please follow and like us:
Content Protection by DMCA.com