XML DOM Parsing
Most browsers have a build-in XML parser to read and manipulate XML.
The parser converts XML into a JavaScript accessible object.
Parsing XML
The XML DOM contains methods (functions) to traverse XML trees, access,
insert, and delete nodes.
However, before an XML document can be accessed and manipulated, it must be
loaded into an XML DOM object.
The parser reads XML into memory and converts it into an XML DOM object that can be accessed with JavaScript.
Load an XML Document
The following JavaScript fragment loads an XML document ("books.xml"):
var xmlDoc;
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET","books.xml",false);
xmlDoc.send(""); |
Code explained:
- Create an XMLHTTP object
- Open the XMLHTTP object
- Send an XML HTTP request to the server
Load an XML String
The following code loads and parses an XML string:
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
return xmlDoc;
}
catch(e)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
return xmlDoc;
} |
Note: Internet Explorer uses the loadXML() method to parse an XML string, while other browsers use the DOMParser object.
Access Across Domains
For security reasons, modern browsers do not allow access across domains.
This means, that both the web page and the XML file it tries to load, must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools domain.
If you want to use the example above on one of your web pages, the XML files you load must be located on your own server.
729,913 sites built with Wix. Make your own
Click here to design a Stunning Flash Website for Free
Wix is a revolutionary web design tool that provides anyone with the possibility to create professional and beautiful websites for free.
With e-commerce features, search engine visibility and many more professional tools, Wix is the ultimate solution for creating a spectacular site while saving tons of money.
|