JavaScript advanced programming Reading Notes (21) XML in JavaScript

Source: Internet
Author: User

I. XML DOM support in IE
IE supports XML based on ActiveX MSXML library.
1. DOM Creation
For each new version of MSXML, different xml dom objects are created, so try to select a new xml dom version.
2. load XML
There are two types of XML loading:
Load XML string: loadXML (xml string)
Load xml file: load (xml file path ). By default, file loading is asynchronous. If you want to change the asynce feature to true, you can change it to synchronous. The readyState and onreadystatechange event processing functions are used for asynchronous file loading. ReadyState has five possible values:
0--DOM has not initialized any information;
1--DOM loading data;
2--DOM completes data loading;
3--DOM is available, but some parts may not;
4--DOM has been fully loaded and can be used.
3. Get XML
Microsoft has added the xml feature for each node, so it is very convenient to obtain XML. See the following example.
4. Incorrect interpretation
You can use parseError to handle errors during XML loading.
The parseError feature is actually an object that contains the following features:
ErrorCode: Error type numeric code, no error is 0
FilePos: location where the error occurs in the file
Line: the row number that encounters an error
Linepos: Position of the character on the line that encountered an error
Reason: An Explanation of the Error
SrcText: Error Code
Url: the URL of the file that causes the error
5. Example:
Copy codeThe Code is as follows:
Function createXMLDOM (){
Var arrSignatures = ["MSXML2.DOMDocument. 5.0", "MSXML2.DOMDocument. 4.0", "MSXML2.DOMDocument. 3.0", "MSXML2.DOMDocument", "Microsoft. XmlDom"];
For (var I = 0; I <arrSignatures. length; I ++ ){
Try {
Var oXmlDom = new ActiveXObject (arrSignatures [I]);
Return oXmlDom;
} Catch (oError ){
}
}
Throw new Error ("MSXML is not installed on your system ");
}
Var oXmlDom = createXMLDOM ();
// Method 1: load the string
OXmlDom. loadXML ("<root> <child/> </rot> ");
// Handle errors
If (oXmlDom. parseError! = 0 ){
Var oError = oXmlDom. parseError;
Alert ("An Error occurred: \ nError Code:" + oError. errorCode
+ "\ NLine:" + oError. line + "\ nLine Pos:" + oError. linepos
+ "\ NReason:" + oError. reason );
} Else {
Var childNodes=oXmlDom.doc umentElement. childNodes;
Console. log (childNodes. length + "" + childNodes [0]. xml); // 1 <child/>
}
// Method 2: load the XML file
OXmlDom. onreadystatechange = function (){
// The document has been loaded.
If (oXmlDom. readyState = 4 ){
If (oXmlDom. parseError! = 0 ){
Var oError = oXmlDom. parseError;
Alert ("An Error occurred: \ nError Code:" + oError. errorCode
+ "\ NLine:" + oError. line + "\ nLine Pos:" + oError. linepos
+ "\ NReason:" + oError. reason );
} Else {
Var childNodes=oXmlDom.doc umentElement. childNodes;
Console. log (childNodes. length + "" + childNodes [0]. xml); // 1 <child/>
}
}
}
OXmlDom. load ("test. xml ");

2. xml dom support in Mozilla
1. Create a DOM
According to the DOM standard, document. implementation has a createDocument () method:
Var oXmlDom = document. implementation. createDocument ("", "", null); the first parameter is the URL of the document namespace, the tag name of the document element, and the document type object (always null, because it is not supported in Mozilla ).
2. load XML
Mozilla supports only one method for loading XML: load (file name ).
Asynchronous or synchronous is determined by async. The default value is asynchronous.
For an XML string, use the DOMParser object to convert it to the DOM. The usage is as follows:
Copy codeThe Code is as follows:
Var oParser = new DOMParser ();
Var oXmlDom = oParser. parseFromString ("<root/>", "text/xml ");

The first parameter of the parseFromString method is an XML string, and the second parameter is a content type. It can be text/xml or application/xml ".
3. Get XML
Because the xml feature provided by Microsoft is not a standard, Mozilla does not support it. Mozilla provides the XMLSerializer object:
Copy codeThe Code is as follows:
Var oSerializer = new XMLSerializer ();
Var sXml = oSerializer. serializeToString (oXmlDom, "text/xml"); in the following example, we can see how to define an xml feature using the defineGetter () method.

4. parsing error
When an error occurs during XML file parsing, the xml dom creates a document to interpret the error. Regular Expressions are often used to output error messages:
Copy codeThe Code is as follows:
Var reError =/> ([\ s \ S] *?) Location :( [\ s \ S] *?) Line Number (\ d +), Column (\ d +): <sourcetext> ([\ s \ S] *?) (? : \-* \ ^ )/;
If(oXmlDom.doc umentElement. tagName = "parsererror "){
ReError. test (oXmlDom. xml );
Alert ("An error occurred: \ nDescription:" + RegExp. $1 + "\ n"
+ "File:" + RegExp. $2 + "\ n"
+ "Line:" + RegExp. $3 + "\ n"
+ "Line Pos:" + RegExp. $4 + "\ n"
+ "Source:" + RegExp. $5 );
}

5. Example
Copy codeThe Code is as follows:
Var oXmlDom = document. implementation. createDocument ("", "<root>", null );
OXmlDom. async = false;
OXmlDom. onload = function (){
Alert ('done ');
}
Var reError =/> ([\ s \ S] *?) Location :( [\ s \ S] *?) Line Number (\ d +), Column (\ d +): <sourcetext> ([\ s \ S] *?) (? : \-* \ ^ )/;
If(oXmlDom.doc umentElement. tagName = "parsererror "){
ReError. test (oXmlDom. xml );
Alert ("An error occurred: \ nDescription:" + RegExp. $1 + "\ n"
+ "File:" + RegExp. $2 + "\ n"
+ "Line:" + RegExp. $3 + "\ n"
+ "Line Pos:" + RegExp. $4 + "\ n"
+ "Source:" + RegExp. $5 );
}
Node. prototype. _ defineGetter _ ("xml", function (){
Var oSerializer = new XMLSerializer ();
Return oSerializer. serializeToString (this, "text/xml ");
});
OXmlDom. load ('test. xml ');
Alert (oXmldom. xml );
Var oNode = oXmlDom.doc umentElement. childNodes [1];
Alert (oNode. xml );

Iii. common interfaces
The following are general interfaces compatible with IE and FireFox:
Copy codeThe Code is as follows:
Function XmlDom (){
If (window. ActiveXObject) {// IE
Var arrSignatures = ["MSXML2.DOMDocument. 5.0", "MSXML2.DOMDocument. 4.0 ",
"MSXML2.DOMDocument. 3.0", "MSXML2.DOMDocument", "Microsoft. XmlDom"];
For (var I = 0; I <arrSignatures. length; I ++ ){
Try {
Var oXmlDom = new ActiveXObject (arrSignatures [I]);
Return oXmlDom;
}
Catch (oError ){
// Ignore
}
}
Throw new Error ("MSXML is not installed on your system .");
} Else if (document. implementation & document. implementation. createDocument ){
Var oXmlDom = document. implementation. createDocument ("", "", null );
OXmlDom. parseError = {valueOf: function (){
Return this. errorCode;
}, ToString: function (){
Return this. errorCode. toString ();
}};
OXmlDom. _ initError __();
OXmlDom. addEventListener ("load", function (){
This. _ checkForErrors __();
This. _ changeReadyState _ (4 );
}, False );
Return oXmlDom;
} Else {
Throw new Error ("Your browser doesn't support an xml dom object .");
}
}
If (isMoz ){
Document. prototype. _ readyState _ = 0;
Document. prototype. onreadystatechange = null;
Document. prototype. _ changeReadyState _ = function (iReadyState ){
This. _ readyState _ = iReadyState;
If (typeof this. onreadystatechange = "function "){
This. onreadystatechange ();
}
};
Document. prototype. _ initError _ = function (){
This. parseError. errorCode = 0;
This. parseError. filepos =-1;
This. parseError. line =-1;
This. parseError. linepos =-1;
This. parseError. reason = null;
This. parseError. srcText = null;
This. parseError. url = null;
};
Document. prototype. _ checkForErrors _ = function (){
If (this.doc umentElement. tagName = "parsererror "){
Var reError =/> ([\ s \ S] *?) Location :( [\ s \ S] *?) Line Number (\ d +), Column (\ d +): <sourcetext> ([\ s \ S] *?) (? : \-* \ ^ )/;
ReError. test (this. xml );
This. parseError. errorcodes =-999999;
This. parseError. reason = RegExp. $1;
This. parseError. url = RegExp. $2;
This. parseError. line = parseInt (RegExp. $3 );
This. parseError. linepos = parseInt (RegExp. $4 );
This. parseError. srcText = RegExp. $5;
}
};
Document. prototype. loadXML = function (sXml ){
This. _ initError __();
This. _ changeReadyState _ (1 );
Var oParser = new DOMParser ();
Var oXmlDom = oParser. parseFromString (sXml, "text/xml ");
While (this. firstChild ){
This. removeChild (this. firstChild );
}
For (var I = 0; I <oXmlDom. childNodes. length; I ++ ){
Var oNewNode = this. importNode (oXmlDom. childNodes [I], true );
This. appendChild (oNewNode );
}
This. _ checkForErrors __();
This. _ changeReadyState _ (4 );
};
Document. prototype. _ load _ = Document. prototype. load;
Document. prototype. load = function (sURL ){
This. _ initError __();
This. _ changeReadyState _ (1 );
This. _ load _ (sURL );
};
Document. prototype. getReadyState = function (){
Return this. _ readyState _;
};
Node. prototype. _ defineGetter _ ("xml", function (){
Var oSerializer = new XMLSerializer ();
Return oSerializer. serializeToString (this, "text/xml ");
});
}

4. other browsers
This book does not cover other browsers, such as Chrome, which is currently very popular. The latest mainstream browsers now support the Mozilla method mentioned above. If not, you can use AJAX to read and process XML.
Author: Artwl
Source: http://artwl.cnblogs.com

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.