JavaScript Advanced Programming Reading notes (21) Xml_javascript techniques in JavaScript

Source: Internet
Author: User
Tags parse error tagname xml attribute
XML DOM support in IE
IE support for XML is based on the MSXML library of ActiveX.
1. Dom Creation
For each new version of MSXML, a different XML DOM object is created, so try to choose a new version of the XML DOM.
2. Loading XML
Loading XML is divided into two types, namely:
Load XML string: Loadxml (XML string)
Load XML file: Load (XML file path). By default, file loading is asynchronous, and if you want to synchronize, change the Asynce attribute to True. The readystate and onReadyStateChange event handler functions are used when loading files asynchronously. There are five possible values for readystate:
0--dom has not initialized any information;
1--dom is loading data;
2--dom completed the data loading;
3--dom is already available, but some parts may not be usable yet;
The 4--dom has been fully loaded and ready for use.
3. Get XML
Microsoft has added XML features to each node, so it's convenient to get XML, see the following example.
4. Explanation Error
You can use ParseError to handle errors that occur during XML loading.
The ParseError attribute is actually an object that contains the following attributes:
ErrorCode: Error Type numeric code, no error 0
Filepos: Where the error occurred in the file
Line: Encountered the wrong row number
Linepos: The position of the character on the line that encountered the error
Reason: An explanation of the error
Srctext: Code that caused the error
URL: The URL of the file that caused the error
5, Examples:
Copy Code code 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 isn't installed on your system");
}
var oxmldom=createxmldom ();
Way One: Load string
Oxmldom.loadxml ("<root><child/></rot>");
Handling 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.documentelement.childnodes;
Console.log (childnodes.length+ "" +childnodes[0].xml);//1 <child/>
}
Mode two: Load XML file
Oxmldom.onreadystatechange = function () {
Document loading complete
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.documentelement.childnodes;
Console.log (childnodes.length+ "" +childnodes[0].xml);//1 <child/>
}
}
}
Oxmldom.load ("Test.xml");

II. XML DOM support in Mozilla
1. Create Dom
The DOM standard states that Document.implementation has a createdocument () method:
var oxmldom=document.implementation.createdocument ("", "", null); Where the first parameter is the namespace URL of the document, the label name of the document element, and the document type object (always null because it is not supported in Mozilla).
2. Loading XML
Mozilla supports only one method of loading XML: Load (filename).
Synchronous or asynchronous is determined by async, which defaults to asynchronous.
If it is an XML string, use the Domparser object to convert to DOM, as follows:
Copy Code code 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 the content type. Can be "text/xml" or "Application/xml".
3. Get XML
The XML feature provided by Microsoft is not a standard, so Mozilla doesn't support it, and Mozilla provides XmlSerializer objects:
Copy Code code 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 attribute with the Definegetter () method.

4. Parse Error
When an error occurs during parsing of an XML file, the XML DOM creates a document to explain the error. You often use regular to output error messages:
Copy Code code as follows:

var reerror =/> ([\s\s]*?) Location: ([\s\s]*?) Line number (\d+), Column (\d+):<sourcetext> ([\s\s]*?) (?:\ -*\^)/;
if (OXmlDom.documentElement.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 Code code 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.documentElement.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.documentelement.childnodes[1];
alert (onode.xml);

third, the common interface
The following are common interfaces for IE and Firefox:
Copy Code code 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 isn't 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.documentElement.tagName = = "ParserError") {
var reerror =/> ([\s\s]*?) Location: ([\s\s]*?) Line number (\d+), Column (\d+):<sourcetext> ([\s\s]*?) (?:\ -*\^)/;
Reerror.test (This.xml);
This.parseError.errorCode =-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");
});
}

four, other browsers
The book does not cover other browsers, such as the now very hot Chrome, the latest version of the mainstream browser has now supported the above the Mozilla method. If not, you can use AJAX to read processing XML.
Author: artwl
Source: http://artwl.cnblogs.com

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.