Most browsers have a built-in XML parser to read and manipulate XML. The parser converts XML into a JavaScript accessible object. Parsing X...
Most browsers have a built-in XML parser to read and manipulate XML.
The parser converts XML into a JavaScript accessible object.
Parsing XML
All modern browsers have a built-in XML parser that can be used to read and manipulate XML.The parser reads XML into memory and converts it into an XML DOM object that can be accessed with JavaScript.
You will learn more about the XML DOM in the next chapter of this tutorial.
There are some differences between Microsoft's XML parser and the parsers used in other browsers. The Microsoft parser supports loading of both XML files and XML strings (text), while other browsers use separate parsers. However, all parsers contain functions to traverse XML trees, access, insert, and delete nodes (elements) and their attributes.
In this tutorial we will show you how to create scripts that will work in both Internet Explorer and other browsers.
Note: When we talk about parsing XML, we often use the term "Nodes" about XML elements.
Loading XML with Microsoft's XML Parser
Microsoft's XML parser is built into Internet Explorer 5 and higher.The following JavaScript fragment loads an XML document ("note.xml") into the parser:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.load("note.xml"); |
Example explained:
- The first line of the script above creates an empty Microsoft XML document object.
- The second line turns off asynchronized loading, to make sure that the parser will not continue execution of the script before the document is fully loaded.
- The third line tells the parser to load an XML document called "note.xml".
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async="false"; xmlDoc.loadXML(txt); |
Note: The loadXML() method is used for loading strings (text), load() is used for loading files.
XML Parser in Firefox and Other Browsers
The following JavaScript fragment loads an XML document ("note.xml") into the parser:var xmlDoc=document.implementation.createDocument ("","",null); xmlDoc.async="false"; xmlDoc.load("note.xml"); |
Example explained:
- The first line of the script above creates an empty XML document object.
- The second line turns off asynchronized loading, to make sure that the parser will not continue execution of the script before the document is fully loaded.
- The third line tells the parser to load an XML document called "note.xml".
var parser=new DOMParser(); var doc=parser.parseFromString(txt,"text/xml"); |
Example explained:
- The first line of the script above creates an empty XML document object.
- The second line tells the parser to load a string called txt.