Reading Notes for JavaScript advanced programming (21): XML in Javascript

Source: Internet
Author: User

Although XML and Dom have become an important part of web development, only IE and Mozilla currently support XML processing on the client.

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 NumberCode, 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:

 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 a string Oxmldom. loadxml ("<root> <child/> </Rot>" );  //  Handling error  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 XML files Oxmldom. onreadystatechange = Function  (){  // Document 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:

 
VaROxmldom = 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:

 
VaROparser =NewDomparser ();VaROxmldom = 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:

 
VaROserializer =NewXmlserializer ();VaRSxml = oserializer. serializetostring (oxmldom, "text/XML ");

In the following example, we can see how to use the definegetter () method to define an XML feature.

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:

 
VaRReerror =/> ([\ s] *?) Location :( [\ s] *?) Line number (\ D +), column (\ D +): <sourcetext> ([\ 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

 VaR Oxmldom = Document. Implementation. createdocument ("", "<root> ",Null  ); Oxmldom. async = False  ; Oxmldom. onload = Function  () {Alert ( 'Done' );}  VaR Reerror =/> ([\ s] *?) Location :( [\ s] *?) Line number (\ D +), column (\ D +): <sourcetext> ([\ 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:

 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 . Documentelement. tagname = "parsererror" ){ VaR Reerror =/> ([\ s] *?) Location :( [\ s] *?) Line number (\ D +), column (\ D +): <sourcetext> ([\ 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" );});} 
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.

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.