The previous article introduced the XML structure and the relationship between nodes.
This article describes the XML Parser built in the browser and how JavaScript loads XML.
Most browsers have built-in XML Parser for reading and operating XML.
The Parser (XML Parser) converts XML into accessible JavaScript objects.
The parser loads XML into the memory and converts it to an xml dom object accessed through JavaScript.
There are some differences between Microsoft's XML Parser and the parser in other browsers. Microsoft's parser supports loading XML files and XML strings (text), while other browsers use separate Resolvers. However, all Resolvers contain functions that traverse the XML tree, access the insertion and deletion of nodes (elements) and their attributes.
Note: When talking about XML parsing, we often use the term XML element: node.
1. ie uses Microsoft's XML parser to load XML
Microsoft's XML parser is built in Internet Explorer 5 and later.
The following JavaScript snippet loads an XML file into the Parser:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async="false";xmlDoc.load("note.xml");
Example:
- The first line of the code above creates an empty Microsoft XML Document Object.
- In the second line, disable asynchronous loading to ensure that the parser will not continue to execute the script until the file is fully loaded.
- The third line tells the parser to load the XML file named "note. xml.
The following JavaScript snippet loads the string TXT into the Parser:
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async="false";xmlDoc.loadXML(txt);
Note: The loadxml () method is used to load strings (text) and load () is used to load files.
Ii. XML parser in Firefox and other browsers
The following JavaScript snippet loads the XML document ("note. xml") into the Parser:
var xmlDoc=document.implementation.createDocument("","",null);xmlDoc.async="false";xmlDoc.load("note.xml");
Example:
- The first line of the code above creates an empty XML Document Object.
- In the second line, disable asynchronous loading to ensure that the parser will not continue to execute the script until the file is fully loaded.
- The third line tells the parser to load the XML file named "note. xml.
The following JavaScript snippet loads the string TXT into the Parser:
var parser=new DOMParser();var xmlDoc=parser.parseFromString(txt,"text/xml");
Example:
- The first line of the code above creates an empty Microsoft XML Document Object.
- The second line tells the parser to load a string named TXT.
Note: The parsefromstring () method of the domparser object is used to load strings (text) and load () is used to load files.
Iii. Cross-origin access
For security reasons, modern browsers do not allow cross-origin access.
If you want to use the above example on your webpage, you must put the XML file on your server. Otherwise, xmldoc. Load () will produce the error "access is denied ".