Javascript reads xml
The Code is as follows:
/**
* Get the set object of the XML file attributes.
* @ Param xmlDoc XML Object
* @ Param name attribute name, for example, user
* @ Return returns an Array object.
* Example XML:
*
*
*
*
* Pig
*
* 27
*
*
*
* Xiaoxia
*
* 26
*
*
*/
Function getXMLArray (xmlDoc, name ){
Var keys = name. split ('.');
Var node = xmlDoc.doc umentElement; // get the root node
Var rtn = new Array ();
Var n = 0;
For (var I = 0; I Var childs = node. childNodes; // obtain the subnode
Var key = keys [I];
For (var k = 0; k Var child = childs [k];
If (child. nodeName = key) {// determines whether the child node matches
If (I = keys. length-1 ){
Rtn [n] = child;
N ++;
} Else {
Node = child;
Break;
}
}
}
}
Return rtn;
}
/**
* Get the value in the object obtained by the getXMLArray function.
* @ Param node object
* @ Param name
* @ Return returns String
*/
Function getValue (node, name ){
Var keys = name. split ('.');
For (var I = 0; I Var childs = node. childNodes; // obtain the subnode
Var key = keys [I];
For (var k = 0; k Var child = childs [k];
If (child. nodeName = key) {// determines whether the child node matches
If (child. childNodes. length = 1 ){
// Return value if there is no byte point
Return child. text;
} Else {
// There are subnodes to continue the analysis
Node = child;
Break;
}
}
}
}
Return "";
}
// Test:
Var xmlDoc = new ActiveXObject ("Microsoft. XMLDOM ");
XmlDoc. async = false;
XmlDoc. loadXML (" Pig 27 Xiaoxia 26 Chapter 25 ");
Var list = getXMLArray (xmlDoc, 'user ');
For (var I = 0; I Var obj = list [I];
Document. write (getValue (obj, 'name. cnname '));
Document. write (getValue (obj, 'age '));
Document. write (' ');
}