Loading and querying XML documents using JavaScript

Source: Internet
Author: User
Tags microsoft dynamics

(1) Loading

The current browsers support XMLHttpRequest objects. We can use this object to load XML documents and create an XML document object. We use an XML file as an example:

 <?  XML version = "1.0" encoding = "UTF-8"  ?>   <  MERs  >     <  Customer  ID  = "01"  City  = "Beijing"  Country  = "China" Name  = "Lenovo"  >       <  Contact  Gender  = "Female"  Title  = "Support"  > Li </  Contact  >     </  Customer  >     < Customer  ID  = "02"  City  = "Amsterdam"  Country  = "The Netherlands"  Name  = "Shell"  >       <  Contact  Gender  = "Male"  Title  = "Sales person"  > Aaron Babbitt </  Contact  >       <  Contact  Gender  = "Female"  Title  = "Sales Manager"  > Daisy Cabell </  Contact  >       <  Contact  Gender = "Male"  Title  = "Sales person"  > Gabriel EADS </  Contact  >     </  Customer  >   </  MERs  > 

LoadedCode:

If(Window. XMLHttpRequest ){//Code for IE7 +, Firefox, chrome, opera, SafariVaRXMLHTTP =NewXMLHttpRequest (); XMLHTTP. Open ("Get", "xmlfile1.xml ",False); XMLHTTP. Send (); xmldoc=XMLHTTP. responsexml; alert (xmldoc. XML );//Only Internet Explorer supportsAlert (XMLHTTP. responsetext );//IE chrome Firefox supports}

Note that in the XMLHttpRequest. Open method, the third parameter is set to synchronous loading or asynchronous loading. If synchronous is false, asynchronous is true. If it is asynchronous, you need to set the callback function.

If you have an XML string, you can also parse the string (PARSE:

VaR STR = "<book>" ; Str = STR + "<title> JavaScript tutorial </title>" ; Str = STR + "<author> Daisy Abbey </author>" ; Str = STR + "</book>" ;  If (Window. domparser ){ //  Code for ie9 +, Firefox, chrome Parser = New  Domparser (); xmldoc = Parser. parsefromstring (STR, "text/XML" );} Else  {Xmldoc = New Activexobject ("Microsoft. xmldom" ); Xmldoc. async = False  ; Xmldoc. loadxml (STR);} alert (xmldoc. childnodes [ 0]. childnodes [0 ]. Textcontent );  //  Result: javascript tutorial 

 

(2) Query

You can use XPath to query XML elements, attributes, and texts. For specific definitions, see w3school.

First, you should understand the XPath expression:

Expression Description
Nodename Select all child nodes of the node.
/ Select from the root node.
// Select the nodes in the document from the current node that matches the selected node, regardless of their location.
. Select the current node.
.. Select the parent node of the current node.
@ Select attributes.

We mainly use two methods to query XML documents, selectnodes (XPath expression) and selectsinglenode (XPath expression ).

Selectnodes returns a nodelist object, that is, all XML nodes that comply with the XPath expression will be returned. You need to traverse the returned results.

Selectsinglenode returns only the first node that complies with the XPath expression or null.

However, because selectsinglenode and selectnodes are only supported by IE, chrome and Firefox use the Evaluate Method to query XML. Therefore, if you need to support multiple browsers, you need to use the encapsulation library. The following is an encapsulation library provided by the Microsoft Dynamics crm sdk, which can be used:

 If ( Typeof (Mylibrary) = "undefined" ) {Mylibrary = {_ Namespace: True  };} Mylibrary = {Name: "Mylibrary" , _ Selectnodes:  Function (Node, xpathexpression ){  If ( Typeof (Node. selectnodes )! = "Undefined" ){  Return  Node. selectnodes (xpathexpression );}  Else  {  VaR Output = [];  VaR Xpathresults = node. Evaluate (xpathexpression, node, mylibrary. _ nsresolver, xpathresult. any_type, Null );  VaR Result = Xpathresults. iteratenext ();  While  (Result) {output. Push (result); Result = Xpathresults. iteratenext ();}  Return  Output ;}}, _ selectsinglenode:  Function  (Node, xpathexpr ){  If ( Typeof (Node. selectsinglenode )! = "Undefined" ){  Return  Node. selectsinglenode (xpathexpr );}  Else  {  VaR Xpe = New  Xpathevaluator ();  VaR Xpathnode = xpe. Evaluate (xpathexpr, node, mylibrary. _ nsresolver, xpathresult. first_ordered_node_type, Null  );  Return (Xpathnode! =Null )? Xpathnode. singlenodevalue: Null  ; }}, _ Selectsinglenodetext:  Function  (Node, xpathexpr ){  VaR X = Mylibrary. _ selectsinglenode (node, xpathexpr );  If  (Mylibrary. _ isnodenull (x )){  Return   Null  ;}  If (Typeof (X. Text )! = "Undefined" ){  Return  X. Text ;}  Else  {  Return  X. textcontent ;}}, _ getnodetext:  Function  (Node ){  If ( Typeof (Node. Text )! = "Undefined" ){  Return Node. Text ;}  Else  {  Return  Node. textcontent ;}}, _ getnodexml:  Function  (Node ){  If ( Typeof (Node. XML )! = "Undefined" ){  Return  Node. xml ;}  Else  { Return ( New  Xmlserializer (). serializetostring (node) ;},_ isnodenull:  Function  (Node ){  If (Node = Null  ){  Return   True  ;}  If (Node. Attributes. getnameditem ("I: Nil ")! = Null ) & (Node. Attributes. getnameditem ("I: Nil"). value = "true")){  Return   True  ;}  Return   False  ;}, _ Nsresolver:  Function  (Prefix ){  VaR NS = { "S": "http://schemas.xmlsoap.org/soap/envelope" , "A": "http://schemas.microsoft.com/xrm/2011/Contracts" , "I": "http://www.w3.org/2001/XMLSchema-instance" , "B": "http://schemas.datacontract.org/2004/07/System.Collections.Generic" , "C": "http://schemas.microsoft.com/xrm/2011/Metadata" };  Return NS [prefix] | Null  ;}} 

The following are examples:

 

1. Return all contact nodes:

VaRNodelist = mylibrary. _ selectnodes (xmldoc, "/customers/customer/contact");For(VaRI = 0; I <nodelist. length; I ++) {Alert (mylibrary. _ getnodexml (nodelist [I]);//Get the XML}

The returned result is:

<Contact gender = "female" Title = "support"> Li LI </contact>
<Contact gender = "male" Title = "sales person"> Aaron Babbitt </contact>
<Contact gender = "female" Title = "Sales Manager"> Daisy Cabell </contact>
<Contact gender = "male" Title = "sales person"> Gabriel EADS </contact>

 

2. Return the customer with ID 02:

Mylibrary. _ selectsinglenode (xmldoc,"/Customers/customer [@ ID = '02']")

The returned result is:

<Customer ID = "02" city = "Amsterdam" Country = "The Netherlands" name = "shell">

<Contact gender = "male" Title = "sales person"> Aaron Babbitt </contact>

<Contact gender = "female" Title = "Sales Manager"> Daisy Cabell </contact>

<Contact gender = "male" Title = "sales person"> Gabriel EADS </contact>

</Customer>

 

3. The returned contact contains the contact name Li:

Mylibrary. _ selectsinglenode (xmldoc,"/Customers/customer/contact [text () = 'Li li']")

The returned result is:

<Contact gender = "female" Title = "support"> Li LI </contact>

 

4. Return the customer with the contact name Li. Note:

Mylibrary. _ selectsinglenode (xmldoc,"/Customers/customer [contact/text () = 'Li li']")

<Customer ID = "01" city = "Beijing" Country = "China" name = "Lenovo">

<Contact gender = "female" Title = "support"> Li LI </contact>

</Customer>

 

5. How to obtain XML, text, and attributes)

(1) Get XML:

VaRNode = mylibrary. _ selectsinglenode (xmldoc,"/Customers/customer/contact [text () = 'Li li']");

VaRNodexml = mylibrary. _ getnodexml (node );

Result: <contact gender = "female" Title = "support"> Li LI </contact>

(2) retrieve text:

Mylibrary. _ selectsinglenode (xmldoc,"/Customers/customer/contact [text () = 'Li li']")

Result: Li

(3) Use the getattribute method to obtain attributes:

mylibrary. _ selectsinglenode (xmldoc, "/customers/customer/contact [text () = 'Li Lil'] " ). getattribute ( " gender " )

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.