XML in the browser

Source: Internet
Author: User
Tags xml attribute
Document directory
  • Simpler Method: load XML files directly
Open XML in the browser

First, open the XML file directly from the browser, and the browser will check its format goodness. If it does not comply with the XML syntax specification, an error is displayed. If the format is good, check whether a style sheet (CSS or XSL) is included. If a style sheet is included, format the XML document in the style sheet and display it. If no, the formatted XML source code is displayed (the display mode is different for different browsers ). note: The browser only checks the XML format, but does not check its validity! How to introduce a style sheet to an XML document? Example:

<?xml version="1.0" standalone="no"?><?xml-stylesheet type="text/css" href="test.css"?>

If you are using XSL, you only need to change the above Type attribute value to text/XSL!

Responsexml attribute of the XMLHTTPRequest object

The responsexml attribute of the XMLHTTPRequest object is used to obtain the XML file returned from the server. If not, it is null. note: Only in the server environment can one request. only an xml dom is returned for a file with the suffix XML. A local XML file is requested and the returned result is still a text file. if you want to use a server script to generate a string, you must add some header information to return XML.

// JS codevar xhr = xhr (); // xhr is the previously written function xhr that allows you to create XMLHttpRequest objects across browsers. open ("get", "test. PHP ", true); xhr. onreadystatechange = function () {If (xhr. readystate = 4 & xhr. status = 200) {// output rootalert(xhr.responsexml.doc umentelement. nodename); // some attributes and methods of Dom 2 core can be used}; xhr. send (null); // PHP codeheader ("Content-Type: text/XML"); // send mime information echo <XML <? XML version = "1.0" encoding = "GBK"?> <Root/> XML;
Simpler Method: load XML files directly

The browser also provides a method to directly load XML files, but it is only supported by Firefox and IE on Windows platforms. Similarly, the implementation between the two is quite different!

Xml dom in IE

Microsoft introduced the activexobject class used to create ActiveX objects in JavaScript. The activexobject constructor has only one parameter-the string code of the ActiveX object to be instantiated. For example, the first version of the xml dom object is Microsoft. xmldom. Therefore, to create an instance of this object, use the following code:

var xmlDom = new ActiveXObject("Microsoft.XmlDom");

Xml dom in IE supports the latest version 5.0. xml dom implementations in IE include:

  • Microsoft. xmldom (original)
  • Msxml2.domdocument
  • Msxml2.domdocument. 3.0
  • Msxml2.domdocument. 4.0
  • Msxml2.domdocument. 5.0

Naturally, whenever possible, everyone will select the latest xml dom version, because the new version will increase the speed and add some new features such as verification. However, if you try to create an ActiveX object that does not exist on the client machine, ie will throw an error and stop all execution. Therefore, to ensure that the correct xml dom version is used and to avoid any other errors, we can create a function to test each xml dom string. If an error occurs, it is captured:

function XMLDOM() {var xmlDomVers = ["Microsoft.XmlDom","MSXML2.DOMDocument","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.5.0"];for (var i=xmlDomVers.length-1;i>=0;i--) {try {var xmlDom = new ActiveXObject(xmlDomVers[i]);return xmlDom;} catch(e) {continue;}}}

The next step is to load XML. Microsoft's xml dom. There are two ways to load XML: loadxml () and load (). The loadxml () method can directly input an XML string to the xml dom. The load () method is used to load XML files from the server. However, the load () method can only load files stored on the same server as pages containing JavaScript, that is, XML files cannot be loaded on other people's servers. The load method also has two file loading modes: synchronous and asynchronous. When a file is loaded in synchronous mode, the JavaScript code will wait until the file is fully loaded before executing the Code; while loading in asynchronous mode, it will not wait, you can use the event processing function to determine whether the file is fully loaded. By default, files are loaded in asynchronous mode. To perform synchronous loading, set async to false:

// Only for ievar xmldom = xmldom (); xmldom. loadxml ("<root/>" registry.alert(xmldom.doc umentelement. nodename); var xml = xmldom (); XML. async = false; // synchronously load XML. load ("test. XML "externalert(xml.doc umentelement. firstchild. nodevalue); // you need to use the readystatechange event to listen to VaR xml2 = xmldom (); xml2.async = true; // you can leave it unspecified. The default value is xml2.onreadystatechange = function () for asynchronous loading () {// The event handler function if (xml2.readystate = 4) must be assigned before the load method is called) {// The meaning of readystate is the same as that of the xhr object. // note that this is not used here. Because activexobject in IE is special, alert (xml2.xml) error occurs when this is used ); // similar to the innerhtml attribute, the XML Attribute in IE returns the source code in the form of an XML string // note that the XML Attribute of the xmldom object in IE is read-only}; xml2.load ("test. XML ");

When you try to load XML into an xml dom object, the XML format may be incorrect whether the loadxml () method or the load () method is used. To solve this problem, Microsoft's parseerror feature of xml dom contains all the information about the problems encountered when parsing XML code.

The parseerror feature is actually an object that contains the following features:

  • Errorcode -- indicates the numeric code of the Error Type (0 if no error exists)
  • Filepos -- location where the error occurs in the file
  • Line -- the row number that encounters an error
  • Linepos -- position of the character on the wrong line
  • Reason -- an explanation of the Error
  • Srctext -- error code
  • URL -- the URL of the file that causes the error (if available)

If you directly set the value of parseerror, it returns the value of errorcode, that is, you can perform this check.

If (xmldom. parseerror = 0) {alert ("no error! ");} Else {var ER = xmldom. parseerror; alert (" XML parsing error! Error message: \ n \ Error Code: "+ er. errorcode + "\ n \ file:" + er. filepos + "\ n \ row:" ++ er. line + "\ n \ character:" + er. linepos + "\ n \ related information:" + er. reason + "\ n \");}
Xml dom in Mozilla

Like other aspects of Mozilla, it provides a more standard xml dom version than IE. Xml dom in Mozilla is actually its JavaScript implementation. That is to say, it not only evolves with browsers, but also can be used reliably on all platforms supported by Mozilla. Therefore, unlike IE, which cannot use xml dom on Macintosh, Mozilla's support spans the boundaries of the platform. In addition, Mozilla's xml dom supports Dom Level 2, while Microsoft only supports Dom Level 1.

The Dom Standard specifies that the document. Implementation object has an available createdocument () method. Mozilla strictly follows this standard and can create xml dom as follows:

var xmlDom = document.implementation.createDocument("","",null);

The three parameters of createdocument () are the document namespace URL, the document element tag name, and a document type object (always null, because there is no support for document type objects in Mozilla ). The previous line of code creates an empty xml dom. To create an xml dom containing a document element, you only need to take the tag name as the second parameter:

var xmlDom = document.implementation.createDocument("","root",null);

This line of code creates an xml dom that represents the XML Code <root/>. If the namespace URL is specified in the first parameter, You can further define the document element:

var xmlDom = document.implementation.createDocument("http://www.x-do.org","root",null);

This line of code creates an xml dom that represents <root xmlns = "http://www.x-do.org"/>

Unlike Microsoft's xml dom, Mozilla only supports one method for loading data: load (). The load () method in Mozilla works in the same way as the load () method in IE. You only need to specify the XML file to be loaded, as well as synchronous or asynchronous (default) loading. If you load XML files synchronously, the code is similar to IE:

VaR xmldom = Document. Implementation. createdocument ("", "root", null); xmldom. async = false; // synchronously load xmldom. Load ("test. xml ");

Unlike IE, there is no readychange event during synchronous loading, but only the load event, and only the loading is complete!

VaR xmldom = document. implementation. createdocument ("", "root", null); xmldom. async = true; // asynchronously load xmldom. onload = function () implements alert(this.doc umentelement. childnodes. item (0 ). tagname); // For JS, you can use the item method and numeric subscript to access the node list. Other languages may not use the subscript}; xmldom. load ("test. XML ");

In addition, Mozilla's xml dom does not support the loadxml () method. To parse an XML string to Dom, you must use the domparser object and use its parsefromstring method to pass in the XML string representation:

VaR xmlparser = new domparser (); var xmldom = xmlparser. parsefromstring ("<root/>", "text/XML"); // This method returns an xml dom object // The second parameter text/XML can also be application/XML, both are used to parse XML // or application/XHTML + XML, which is used to parse XHTML. Only these three MIME types can be used.

Methods for obtaining XML strings that correspond to directly parsing XML strings. xml dom objects in IE have read-only XML attributes, while Mozilla does not. However, mozilla provides xmlserializer objects that can be used for the same purpose:

VaR serializer = new xmlserializer (); var xmlstr = serializer. serializetostring (xmldom, "text/XML"); // xmldom is an xml dom Node object // and text/XML can also be application/XML

Mozilla's implementation method is very troublesome for XML parsing errors. Unlike IE, it provides an object to indicate errors, but returns error information as an XML document to obtain specific error information, you must also use a string to parse it!

VaR xmlparser = new domparser (); var xmldom = xmlparser. parsefromstring ("<root> <child> </root>", "text/XML" contains multiple alert(xmldom.doc umentelement. nodename); // parsererror will be returned because var serializer = new xmlserializer (); var STR = serializer. serializetostring (xmldom, "text/XML"); alert (STR); // The output is similar to the following content <parsererror xmlns = "http://www.mozilla.org/newlayout/xml/parsererror.xml"> XML parsing error: mismatched mark. expectation: & lt;/Child & gt ;. Location: file: // E:/XML/test.html row: 1, column: 16: <sourcetext> & lt; root & gt; & lt; Child & gt; & lt;/root & gt; ------------- ^ </sourcetext> </parsererror>

The regular expression is used to extract the error information such as the row number! However, due to different browser language settings, it is difficult to use regular expressions! As you can see, although Mozilla implements more standard xml dom, It is very inconvenient to use it!

Cross-browser xml dom Constructor

Cross-browser authentication is only compatible with IE on Mozilla and windows. For other browsers, You can downgrade and use the xhr responsexml, although the xhr object does not provide any advanced and convenient methods for this attribute, it is enough to read XML!

If (document. implementation & document. implementation. createdocument) {// w3cvar getxmldom = function () {// get an xmldom object return document. implementation. createdocument ("", "", null) ;}, loadxmlfile = function (xmldom, URL, callback) {If (xmldom. async === true) {xmldom. onload = function () {If (xmldom.doc umentelement. nodename = "parsererror") {Throw new error ("XML Parse error:" specify xmldom.doc umentelement. firstchild. node Value);} else {callback. call (xmldom) ;};} xmldom. load (URL); Return xmldom;}, loadxmlstring = function (xmldom, S) {var P = new domparser (); var newdom = P. parsefromstring (S, "text/XML"); If (newdom.doc umentelement. nodename = "parsererror") {Throw new error ("XML Parse error:" using newdom.doc umentelement. firstchild. nodevalue);} while (xmldom. firstchild) {xmldom. removechild (xmldom. firstchild) ;}for (VAR I = 0, N; I <newdom. Childnodes. length; I ++) {n = xmldom. importnode (newdom. childnodes [I], true); // importnode is used to import nodes from other documents to the current document. // The True parameter is used to import the child node xmldom at the same time. appendchild (n) ;}return xmldom ;}, getxml = function (xmlnode) {var S = new xmlserializer (); Return S. serializetostring (xmlnode, "text/XML") ;};} else if (window. activexobject) {// ievar getxmldom = function () {return New activexobject ("Microsoft. xmldom ") ;}, loadxmlfile = function (xmldom, URL, callback) {xmldom. onreadystatechange = function () {If (xmldom. readystate = 4) {If (xmldom. parseerror. errorcode = 0) {callback. call (xmldom);} else {Throw new error ("XML Parse error:" + xmldom. parseerror. reason) ;}}; xmldom. load (URL); Return xmldom;}, loadxmlstring = function (xmldom, S) {xmldom. loadxml (s); If (xmldom. parseerror. errorcode! = 0) {Throw new error ("XML Parse error:" + xmldom. parseerror. reason);} return xmldom;}, getxml = function (xmlnode) {return xmlnode. XML ;};}

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.