Compatible with xml processing functions of IE, FireFox, Chrome, and other browsers. js code _ javascript skills

Source: Internet
Author: User
Tags xsl
JavaScript is compatible with xml processing functions (xml synchronous asynchronous loading, xsl conversion, selectSingleNode, and selectNodes) in IE, FireFox, Chrome, and other browsers. It is often a headache for browser compatibility when writing web pages that process xml. So I encapsulate common xml operations as functions. After a period of improvement, it is very stable and comfortable to use.
Functions have --
Xml_loadFile: xml synchronous/asynchronous loading.
Xml_transformNode: xsl conversion.
Xml_text: the node text.
SelectSingleNode: select a single node based on XPath.
SelectNodes: Select multiple nodes based on XPath.
All code (zyllibjs_xml.js )--

The Code is as follows:


/*
Zyllibjs_xml
XML Processing
@ Author zyl910
Note --
1. Chrome cannot read local files due to its security mechanism restrictions.
Reference
~~~~~~~~~
Http://www.jinlie.net /? P = 302
XML file loading in Chrome
Update
~~~~~~
[2011-11-02]
Definition.
[2011-11-09]
Xml_loadFile: add the isError parameter to the callback function.
[2011-11-21]
SelectSingleNode
SelectNodes
*/
// Load the XML file and return the XML file Node
// Return: an object is returned when the operation succeeds (xml Document Object is returned in synchronous mode and operation object is returned in asynchronous mode). If the operation fails, null is returned.
// XmlUrl: the url of the xml file.
// FuncAsync: callback function. function onload (xmlDoc, isError ){...}
Function xml_loadFile (xmlUrl, funcAsync)
{
Var xmlDoc = null;
Var isChrome = false;
Var asyncIs = (null! = FuncAsync); // whether it is asynchronously loaded. When funcAsync is not empty, asynchronous loading is used; otherwise, synchronous loading is used.
// Check parameters
If ("" = xmlUrl) return null;
If (asyncIs)
{
If ("function "! = Typeof (funcAsync) return null;
}
// Create an XML Object
Try
{
XmlDoc = new ActiveXObject ("Microsoft. XMLDOM"); // Support IE
}
Catch (ex)
{
}
If (null = xmlDoc)
{
Try
{
// Support Firefox, Mozilla, Opera, etc
XmlDoc = document. implementation. createDocument ("", "", null); // create an empty XML document Object.
}
Catch (ex)
{
}
}
If (null = xmlDoc) return null;
// Load the XML document
XmlDoc. async = asyncIs;
If (asyncIs)
{
If (window. ActiveXObject)
{
XmlDoc. onreadystatechange = function (){
If (xmlDoc. readyState = 4)
{
Var isError = false;
If (null! = XmlDoc. parseError)
{
IsError = (0! = XmlDoc. parseError. errorCode); // 0 succeeded, not 0 failed.
}
FuncAsync (xmlDoc, isError );
}
}
}
Else
{
XmlDoc. onload = function (){
FuncAsync (xmlDoc, false );
}
}
}
Try
{
XmlDoc. load (xmlUrl );
}
Catch (ex)
{
// Alert (ex. message) // If the browser is Chrome, the exception will be caught: Object # (a Document) has no method "load"
IsChrome = true;
XmlDoc = null;
}
If (isChrome)
{
Var xhr = new XMLHttpRequest ();
If (asyncIs) // asynchronous
{
Xhr. onreadystatechange = function (){
If (xhr. readyState = 4)
{
FuncAsync (xhr. responseXML, xhr. status! = 200 );
}
}
Xhr. open ("GET", xmlUrl, true );
In try // asynchronous mode, errors are handled by the callback function.
{
Xhr. send (null );
}
Catch (ex)
{
FuncAsync (null, true );
Return null;
}
Return xhr; // Note: XMLHttpRequest is returned. We recommend that you use null to test the return value in asynchronous mode.
}
Else // Synchronization
{
Xhr. open ("GET", xmlUrl, false );
Xhr. send (null); // The caller can handle exceptions in synchronization mode.
XmlDoc = xhr. responseXML;
}
}
Return xmlDoc;
}
// Use XSLT to convert an XML document into a string.
Function xml_transformNode (xmlDoc, invalid DOC)
{
If (null = xmlDoc) return "";
If (null = callback DOC) return "";
If (window. ActiveXObject) // IE
{
Return xmlDoc. transformNode (invalid DOC );
}
Else // FireFox, Chrome
{
// Define the effectprocesor object
Var effectprocessor = new effectprocessor ();
Effectprocessor. importStylesheet (invalid DOC );
// TransformToDocument Method
Var result = effectprocessor. transformToDocument (xmlDoc );
Var xmls = new XMLSerializer ();
Var rt = xmls. serializeToString (result );
Return rt;
}
}
// Obtain the node text
Function xml_text (xmlNode)
{
If (null = xmlNode) return "";
Var rt;
If (window. ActiveXObject) // IE
{
Rt = xmlNode. text;
}
Else
{
// FireFox, Chrome ,...
Rt = xmlNode. textContent;
}
If (null = rt) rt = xmlNode. nodeValue; // XML DOM
Return rt;
}
// Add method. To be compatible with FireFox and Chrome.
If (! Window. ActiveXObject)
{
XMLDocument. prototype. selectSingleNode = Element. prototype. selectSingleNode = function (xpath)
{
Var x = this. selectNodes (xpath)
If (! X | x. length <1) return null;
Return x [0];
}
XMLDocument. prototype. selectNodes = Element. prototype. selectNodes = function (xpath)
{
Var xpe = new XPathEvaluator ();
Var nsResolver = xpe. createNSResolver (this. ownerDocument = null? This.doc umentElement: this.ownerDocument.doc umentElement );
Var result = xpe. evaluate (xpath, this, nsResolver, 0, null );
Var found = [];
Var res;
While (res = result. iterateNext ())
Found. push (res );
Return found;
}
}


XML file loading in Chrome
Chrome does not support loading XML documents. If you have found it online, you need to solve the problem as follows:

The Code is as follows:


Function loadXMLDoc (xml_name)
{
Var xmlDoc;
Try
{
XmlDoc = new ActiveXObject ("Microsoft. XMLDOM"); // Support IE
}
Catch (e)
{
Try
{
// Support Firefox, Mozilla, Opera, etc
XmlDoc = document. implementation. createDocument ("", "", null); // create an empty XML document Object.
}
Catch (e)
{
Alert (e. message );
}
}
// Load the XML document
Try
{
XmlDoc. async = false; // disable asynchronous loading
XmlDoc. load (xml_name );
}
Catch (e)
{
// Alert (e. message) if the browser is Chrome, the exception will be caught: Object # (a Document) has no method "load", so, the following implementation supports chrome to load XML documents (just a rough write)
Var xhr = new XMLHttpRequest ();
Xhr. open ("GET", xml_name, false );
Xhr. send (null );
XmlDoc = xhr.responseXML.doc umentElement;
}
Return xmlDoc;
}


BTW, different browsers load XML strings.
IE uses the loadXML () method to parse XML strings:

The Code is as follows:

XmlDoc. loadXML (xml_str );


Using DOMParser objects such as FireFox to parse XML strings:

The Code is as follows:


Var parseXml = new DOMParser ();
Var doc = parseXml. parseFromString (xml_str, "text/xml ");

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.