Query and load of XML documents in JavaScript

Source: Internet
Author: User
Tags cdata tag name xpath

Most of the methods defined by document are production methods, primarily used to create various types of nodes that can be inserted into a document. The common Document methods are:

Method

Describe

CreateAttribute ()

creates a new name with the specified Attr node.

Createcomment ()

creates a new name with the specified string . Comment node.

CreateElement ()

creates a new one with the specified tag name. Element node.

createTextNode ()

creates a new name with the specified text . Textnode node.

getElementById ()

returns the document with the specified The Element node of the id attribute .

getElementsByTagName ()

returns all the names in the document that have the specified tag name. Element node.

Load

You can load some XML with XML DOM objects. Microsoft's XML DOM has two methods of loading XML: Loadxml () and load ().

The Loadxml () method can enter an XML string directly into the XML DOM:

The code is as follows Copy Code

Oxmldom.loadxml (' <root><child/></root> ');

The load () method is used to upload the XML file from the server. However, the load () method can only load files that contain JavaScript in a file stored on the same server, that is, you cannot load an XML file through another person's server.

There are also two modes of loading files: synchronous and asynchronous. When you load a file in synchronous mode, the JavaScript code waits for the file to be fully loaded before proceeding with the code, while loading in asynchronous mode does not wait, you can use the event handler function to determine whether the file is fully loaded.

By default, files are loaded in asynchronous mode, and for synchronous loading, you simply set the Async property to False:

JS Code
1.

The code is as follows Copy Code
Oxmldom.async = false;
Oxmldom.async = false;

Then use the load () method and give the file name to load:

JS Code
1.

The code is as follows Copy Code
Oxmldom.load (' Test.xml ');
Oxmldom.load (' Test.xml ');

After this line of code is executed, Oxmldom contains a DOM document that represents the structure of the XML file, so that all the properties and methods of the DOM can be used.


To load files asynchronously, use the ReadyState property and the onReadyStateChange event handler function:

The ReadyState property has a possible value:

0--dom has not initialized any of the information
1--dom is loading data
2--dom completes the data loading
3--dom is already available, but some parts may not work
The 4--dom has been fully loaded and can be used
Once the value of the ReadyState property changes, the ReadyStateChange event is triggered, and if you use the onReadyStateChange event handler, you can send a notification when the DOM is fully loaded, and you must call load () The onReadyStateChange event handler function is assigned before the method, such as:

JS Code

  code is as follows copy code
oxmldom.onreadystat Echange = function () {  
   if (oxmldom.readystate = 4) {  
&NBSP;&NBSP;&NBSP;&N bsp;       alert (' Done ');  
   }  
};   
Oxmldom.load ("Test.xml"); 
Oxmldom.onreadystatechange = function () {
 if ( Oxmldom.readystate = = 4 {
           alert (' Done ');
 }
};
Oxmldom.load ("Test.xml");

Note: Use the oxmldom instead of the This keyword in the event-handling function code. This is special for ActiveX objects: Using this keyword can cause unpredictable errors.

Whether you are loading files synchronously or asynchronously, the load () method may accept partial, relative, or complete XML file paths, as follows:

The code is as follows Copy Code

Oxmldom.load (' Test.xml ');

Oxmldom.load ('.. /test.xml ');

Oxmldom.load (' Http://www.mydomanin.com/test.xml ');

Inquire

You can use XPath for querying XML for elements, attributes, and text. A specific definition can be referred to W3school.

The first thing you should know about XPath expressions:

Description of expression
NodeName selects all child nodes of this node.
/Selected from the root node.
Select the nodes in the document from the current node that matches the selection, 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, which means that all XML nodes that conform to XPath expressions will be returned, and you need to traverse the returned results.

selectSingleNode returns only the first node that conforms to an XPath expression, or returns NULL.

Here are a few examples:

1. Return all contact nodes:

The code is as follows Copy Code

var nodelist = xmldoc.selectnodes ("/customers/customer/contact");
for (var i = 0; i < nodelist.length; i++) {
alert (nodelist[i].xml);
}

The result returned 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 customer with ID 02:

The code is as follows Copy Code
Xmldoc.selectsinglenode ("/customers/customer[@id = ' 02 ']")

The result returned is:

<

The code is as follows Copy Code

Customer id= "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. Return containing contact named Li Li:

The code is as follows Copy Code

Xmldoc.selectsinglenode ("/customers/customer/contact[text () = ' li Li ']")

The result returned is:

The code is as follows Copy Code

<contact gender= "female" title= "Support" >li li</contact>

4. Return the customer containing the contact name Li Li. Note the difference from 3:

The code is as follows Copy Code

Xmldoc.selectsinglenode ("/customers/customer[contact/text () = ' li Li ']");

<customer id= "city=" Beijing "country=" "" "Name=" Lenovo ">

<contact gender= "female" title= "Support" >li li</contact>

</Customer>

5. How to get XML, text, and attributes (attribute)

(1) Get XML: use. XML, such as

The code is as follows Copy Code
Xmldoc.selectsinglenode ("/customers/customer/contact[text () = ' li Li ']"). xml

The results are:

The code is as follows Copy Code
<contact gender= "female" title= "Support" >li li</contact>

(2) obtain

The code is as follows Copy Code
Text:xmlDoc.selectSingleNode ("/customers/customer/contact[text () = ' li Li ']"). Text

The result: Li Li

(3) Get the attribute using the GetAttribute method:

The code is as follows Copy Code
Xmldoc.selectsinglenode ("/customers/customer/contact[text () = ' li Li ']"). getattribute ("gender")

Finally, look at a complete example

The code is as follows Copy Code

< script language = "JavaScript" >
<!--
var doc = new ActiveXObject ("Msxml2.domdocument"); Ie5.5+,createobject ("Microsoft.XMLDOM")


Loading documents
Doc.load ("B.xml");

To create a file header
var p = doc.createprocessinginstruction ("xml", "version= ' 1.0 ' encoding= ' gb2312 '");

Add File Headers
Doc.appendchild (P);

To get the root contact when loading directly
var root = doc.documentelement;

Create root contacts in two ways
var root = doc.createelement ("Students");
var root = Doc.createnode (1, "Students", "");

Creating Child contacts
var n = doc.createnode (1, "Ttyp", "");

Specify Child Contact text
N.text = "This is a test";

Create Sun Contact
var o = doc.createelement ("Sex");
O.text = "male"; Specify its text

Creating properties
var r = doc.createattribute ("id");
R.value = "Test";

Add properties
N.setattributenode (R);

Create a second property
var r1 = Doc.createattribute ("class");
R1.value = "tt";

Add properties
N.setattributenode (R1);

Delete Second Property
N.removeattribute ("class");

Add Sun Contact
N.appendchild (o);

Add text Contacts
N.appendchild (Doc.createtextnode ("This is a text node.");

Add a Comment
N.appendchild (Doc.createcomment ("This is a Commentn"));

Add Child contacts
Root.appendchild (n);

Copy Contacts
var m = N.clonenode (true);

Root.appendchild (m);

Delete a contact
Root.removechild (root.childnodes (0));

Create a data segment
var c = doc.createcdatasection ("This is a CDATA");
C.text = "Hi,cdata";
Adding data segments
Root.appendchild (c);

Add Root Contact
Doc.appendchild (root);

Find Contacts
var a = Doc.getelementsbytagname ("Ttyp");
var a = Doc.selectnodes ("//ttyp");

Show the properties of the modified contact
for (var i = 0; I < A.length;i + +)
{
alert (a[i].xml);
for (var j = 0; J < A[i].attributes.length;j + +)
{
alert (a[i].attributes[j].name);
}
}

modifying nodes, using XPath to locate nodes
var B = Doc.selectsinglenode ("//ttyp/sex");
B.text = "female";

    //alert (doc.xml);
 
    //XML save (required on server, client with FSO)
     //Doc.save ();
    
    //view root contact XML
      if (n)
& nbsp;     {
        alert (n.ownerdocument.xml);
   }
 
 //-->
 </script

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.