XML tool class for XmlUtils JS operations

Source: Internet
Author: User
Tags processing instruction tagname

The demo uses extjs to print the json array.
Js code (XmlUtils. js ):

Copy codeThe Code is as follows :/**/
Function XmlUtils (config ){
/* Define private attributes */
This. isIE = !! (Window. attachEvent &&! Window. opera );
This. init ();
If (config ){
This. dataType = config. dataType = 'json '? 'Json': 'array ';
If (config. xmlPath) this. loadXml (config. xmlPath );
}
}
XmlUtils. prototype = {
XmlDoc: null,
XmlPath: null,
DataType: null,
/**
* Initialization
*/
Init: function (){
If (this. isIE ){
Var activexArr = ["MSXML4.DOMDocument", "MSXML3.DOMDocument", "MSXML2.DOMDocument", "MSXML. DOMDocument", "Microsoft. XmlDom"];
For (I = 0; I <activexArr. length; I ++ ){
Try {
This. xmlDoc = new ActiveXObject (activexArr [I]);
} Catch (e ){}
}
} Else {
This. xmlDoc = document. implementation. createDocument ("", "", null );
}
},

/**
* Load the xml file. parameters:
* @ Param {string} xmlPath: Path of the loaded xml file;
* @ Return {Object} true normal loading; false loading failed
*/
LoadXml: function (xmlPath ){
Try {
This. xmlDoc. async = false;
This. xmlDoc. load (xmlPath );
This. xmlPath = xmlPath;
Return true;
} Catch (e ){
Return false;
}
},

/**
* Load an XML string
* @ Param {Object} XMLString
*/
LoadXmlString: function (xmlString ){
If (this. isIE ){
This. xmlDoc. loadXML (xmlString );
} Else {
Var parser = new DOMParser ();
This. XMLDoc = parser. parseFromString (xmlString, "text/xml ");
}
},

/**
* Determine whether a node has a subnode.
* @ Param {Object} node
* @ Return {Object} returns true if a subnode exists. Otherwise, false is returned.
*/
HasChildNodes: function (node ){
Return node. hasChildNodes ();
},

/**
* Determine whether a node has attributes.
* @ Param {Object} node
* @ Return {Object} returns true if there is an attribute; otherwise, false.
*/
HasAttributes: function (node ){
Return (node. attributes. length> 0 )? True: false;
},

/**
* Determine whether a node is a text node, including a text node with CDATA segments.
* @ Param {Object} node
* @ Return {Object} is a text node. true is returned; otherwise, false is returned.
*/
IsTextNode: function (node ){
Var type = this. getNodeType (node );
Return (type = 3 | type = 4 )? True: false;
},

/**
* Returns the root node.
* @ Return {Object} Root Node
*/
GetRoot: function (){
Return this.xmlDoc.doc umentElement;
},

/**
* Return the first subnode of the node. If no parameter is specified, the first subnode of the root node is returned.
* @ Param {Object} node
* @ Return {Object} The first subnode of the node
*/
GetFirstChild: function (node ){
Return node? Node. firstChild: this. getRoot (). firstChild;
},

/**
* Returns the last child node of the node. If no parameter is specified, the first child node of the root node is returned.
* @ Param {Object} node
* @ Return {Object} The Last subnode of the node
*/
GetLastChild: function (node ){
Return node? Node. lastChild: this. getRoot (). lastChild;
},

/**
* Return the next node of the node. If no parameter exists, return the first subnode of the root node.
* @ Param {Object} node
* @ Return {Object} the next node of the node
*/
GetNextNode: function (node ){
Return node? Node. nextSibling: null;
},

/**
* Returns the previous node of the root node. If no parameter exists, the first subnode of the root node is returned.
* @ Param {Object} node
* @ Return {Object} the previous node of the node
*/
Getpreviusnode: function (node ){
Return node? Node. previussibling: null;
},

/**
* Return the child node of the node. If there is no parameter, null is returned.
* @ Param {Object} node
* @ Return {Object} All subnodes of the node
*/
GetChildNodes: function (node ){
Return (node & this. hasChildNodes (node ))? Node. childNodes: null;
},

/**
* Returns the parent node of the node. If no parameter is specified, null is returned.
* @ Param {Object} node
* @ Return {Object} parent node
*/
GetParentNode: function (node ){
Return node? Node. parentNode: null;
},

/**
* Return the text value of the node Array Based on the node name. parameters:
* @ Param {string or object} nodeName: node name;
* @ Return {object} indicates that the node array exists. If the node does not exist, null is returned.
*/
GetNodesTextByName: function (nodeNames ){
Return nodeNames? (This. dataType = 'json '? This. getJsonNodesTextByName (nodeNames): this. getArryNodesTextByName (nodeNames): null;
},

/**
* Return the text value of a common array of Nodes Based on the node name. parameters:
* @ Param {string or object} nodeName: node name;
* @ Return {object} a normal array of returned nodes exists on the node.
*/
GetArryNodesTextByName: function (nodeNames ){
Var rs = [];
// Returns the Normal Array format
Switch (typeof (nodeNames )){
Case 'string ':
Var nodes = this. getNodesByTagName (nodeNames );
For (var I = 0; I <nodes. length; I ++ ){
Rs. push (nodes [I]. text );
}
Break;
Case 'object ':
Var subRs;
Var nodes;
For (var I = 0; I <nodeNames. length; I ++ ){
Nodes = this. getNodesByTagName (nodeNames [I]);
SubRs = [];
For (var j = 0; j <nodes. length; j ++ ){
SubRs. push (nodes [j]. text );
}
Rs. push (subRs );
}
Break;
}
Return rs;
},

/**
* Return the node JSON array text value based on the node name. parameters:
* @ Param {string or object} nodeName: node name;
* @ Return {object} The returned node JSON array exists. If the node does not exist, null is returned.
*/
GetJsonNodesTextByName: function (nodeNames ){
Var rs = null;
// Return the JSON array format
Switch (typeof (nodeNames )){
Case 'string ':
Eval ('rs = {'+ nodeNames +': []} ');
Var nodes = this. getNodesByTagName (nodeNames );
For (var I = 0; I <nodes. length; I ++ ){
Eval ('rs. '+ nodeNames +'. push ({'+ nodeNames + I +': nodes [I]. text })');
}
Break;
Case 'object ':
Rs = {};
Var nodes;
For (var I = 0; I <nodeNames. length; I ++ ){
Eval ('rs. '+ nodeNames [I] +' = [] ');
Nodes = this. getNodesByTagName (nodeNames [I]);
For (var j = 0; j <nodes. length; j ++ ){
Eval ('rs. '+ nodeNames [I] +'. push ({'+ nodeNames [I] + j +': nodes [j]. text })');
}
}
Break;
}
Return rs;
},

/**
* Get the node according to the node attributes. parameters:
* @ Param {String} key: property name. The default value is id.
* @ Param {String} value: Attribute value
* @ Return {String} a node array that meets the condition.
*/
GetNodesByAttribute: function (key, value ){
Key = key? Key: 'id ';
Value = value? Value :'';
Return id? This. xmlDoc. getElementById (id): null;
},

/**
* Get the node according to the node name. parameters:
* @ Param {string} tagName: node name
* @ Return {string} specifies the node or node array of the node name and position.
*/
GetNodesByTagName: function (tagName ){
Return tagName? This. xmlDoc. getElementsByTagName (tagName): null;
},

/**
* Return the index Node Based on the Node path. parameters:
* @ Param {string} xPath: Node path
* @ Param {number} index: The index location. If it is null or 0, all the searched nodes are returned.
* @ Return {string} specifies the node or node array of the node name and position.
*/
GetNodesByXpath: function (xPath, index ){
If (! XPath) return null;
Var nodes = this. xmlDoc. selectNodes (xPath );
Var len = nodes. length;
If (! Index | index> len | index <0) return nodes;
For (var I = 0; I <len; I ++ ){
If (I = index-1) return nodes [I];
}
},

/**
* Get the specified node text. parameters:
* @ Param {object} node: node
* @ Return {string} indicates the node text. If it is null, null is returned.
*/
GetText: function (node ){
Return node? Node. text: null;
},

/**
* Get the specified node name. parameters:
* @ Param {object} node: node
* @ Return {string} node name. If it is null, null is returned.
*/
GetTagName: function (node ){
Return node? Node. nodeName: null;
},

/**
* Return node type, parameter:
* @ Param {object} node: node
* @ Return {string} node type. If it is null, null is returned.
* 1-element
* 2-attribute
* 3-text
* 4-cdata
* 5-entity reference
* 6-entity
* 7-pi (processing instruction)
* 8-comment
* 9-document
* 10-document type
* 11-document fragment
* 12-notation
*/
GetNodeType: function (node ){
Return node? Node. nodeType: null;
},

/**
* Create a node. parameters:
* @ Param {string} nodeName: node name, required
* @ Param {string} text: node text, which can be empty
* @ Param {Object} attributes: attribute value-JSON array, which can be empty. For example, {id: 'id001', name: 'name001 '}
* @ Param {Object} node: the node to add a subnode. If it is null, the newly created node is returned.
* @ Param {Boolean} cdata: whether to generate a node with CDATA segments; true: generate; false: do not generate
* @ Return {Object}: the node created. If an exception exists, null is returned.
*/
CreateNode: function (nodeName, text, attributes, node, cdata ){
If (this. isIE ){
// Create a child contact
Var childNode = this. xmlDoc. createElement (nodeName );
// Create a text node
Var textNode = cdata = true? This. xmlDoc. createCDATASection (text): this. xmlDoc. createTextNode (text );
ChildNode. appendChild (textNode );
// Add attributes
For (var I in attributes ){
This. createAttribute (childNode, I, attributes [I]);
};

Return node? Node. appendChild (childNode): childNode;
} Else {
Alert ('ff after creating a node .');
Return null;
}
},

/**
* Create a node with CDATA segments. parameters:
* @ Param {string} nodeName: node name, required
* @ Param {string} text: node text, which can be empty
* @ Param {Object} attributes: attribute value-JSON array, which can be empty. For example, {id: 'id001', name: 'name001 '}
* @ Param {Object} node: the node to add a subnode. If it is null, the newly created node is returned.
*/
CreateCDATANode: function (nodeName, text, attributes, node ){
This. createNode (nodeName, text, attributes, node, true );
},

/**
* Create node attributes. parameters:
* @ Param {Object} node: node, required
* @ Param {String} key: attribute name, required
* @ Param {Object} value: attribute value, required
* @ Param {Object} node: return the node with the new attribute.
* @ Return {Object} adds the attribute node. If an exception occurs, null is returned.
*/
CreateAttribute: function (node, key, value ){
If (this. isIE ){
If (! Key) return;
Var attr = this. xmlDoc. createAttribute (key );
Attr. value = value? Value :"";
Node. setAttributeNode (attr );
Return node;
} Else {
Alert ('ff after creating a node .');
Return node;
}
Return null;
},

/**
* Add the node to the root node. parameters:
* @ Param {Object} node: node
* @ Return {Object} returns null if an exception occurs.
*/
AddNodeToRoot: function (node ){
If (! Node) return null;
This. getRoot (). appendChild (node );
Return node;
},

/**
* Add the node to another node. parameters:
* @ Param {Object} node: node
*/
AddNode: function (node, childNode ){
Return (node & childNode )? Node. appendChild (childNode): false;
},

/**
* Remove the node from the parent node. parameters:
* @ Param {Object} newNode: the node to be replaced
* @ Param {Object} oldNode: the node to be replaced
*/
ReplaceChild: function (newNode, oldNode ){
Var parentNode = oldNode. parentNode;
If (! NewNode |! OldNode |! ParentNode) return;
ParentNode. replaceChild (newNode, oldNode );
},

/**
* Remove the node from the parent node. parameters:
* @ Param {Object} node: the node to be removed
*/
RemoveChild: function (node ){
If (! Node |! Node. parentNode) return;
Node. parentNode. removeChild (node );
},

/**
* Remove all child nodes of a node. parameters:
* @ Param {Object} node: parent node
*/
RemoveChildNodes: function (node ){
If (node & this. hasChildNodes (node )){
Var childNodes = node. childNodes;
For (var I = 0; I <childNodes. length; I ++ ){
Node. removeChild (childNodes [0]);
}
}
},

/**
* Set the node attribute value. If the attribute value does not exist, it is created. parameters:
* @ Param {Object} node: node to be set
* @ Param {String} key: name of the property to be set
* @ Param {String} value: attribute value to be set
*/
SetAttribute: function (node, key, value ){
This. createAttribute (node, key, value );
},

/**
* Set the text of the text node. parameters:
* @ Param {Object} node: node to be set
* @ Param {String} text: text to be set
*/
SetText: function (node, text ){
If (this. isTextNode (node) node. text = text;
},

/**
* Append text to the text node. parameters:
* @ Param {Object} node: node to be set
* @ Param {String} text: text to be set
*/
AppendText: function (node, text ){
If (this. isTextNode (node) node. appendData (text );
},

/**
* Output xml. If it is null, the root node text is output. parameters:
* @ Param {Object} node: node to be output
*/
ToString: function (node ){
Node = node? Node: this.xmlDoc.doc umentElement;
If (typeof node = 'string') return node;
Return this. isIE? Node. xml: new XMLSerializer (). serializeToString (node );
}
}

Test xml file (book. xml ):Copy codeThe Code is as follows: <? Xml version = "1.0" encoding = "UTF-8"?>
<Root>
<Book>
<Name> Travel Notes to the west </name>
<Author> Wu chengen </author>
</Book>
<Book>
<Name> Dream of Red Mansions </name>
<Author> CAO Xueqin </author>
</Book>
<Book>
<Name> Romance of the Three Kingdoms </name>
<Author>
<Name> Shi Nai </name>
<Sex> male </sex>
</Author>
</Book>
<Book>
<Name> Water Margin </name>
<Author> Luo Guanzhong </author>
</Book>
</Root>

Html code (test.html ):Copy codeThe Code is as follows: <Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Script language = "JavaScript" type = "text/javascript" src = "../Ext/ext-base.js"> <! --

// --> </Script>
<Script language = "JavaScript" type = "text/javascript" src = "../Ext/ext-all.js"> <! --

// --> </Script>
<Title> test xml </title>
<Script src = "XmlUtils. js"> </script>
</Head>
<Body>
<Div id = 'xmloptest'> </div>
</Body>
<Script type = "text/javascript"> <! --
/**
* Config parameter: xmlPath file address. dataType Data Format: json or arry. The default value is array.
*/
Var xmlUtils = new XmlUtils ({xmlPath: "book. xml", dataType: 'json '});
Alert (xmlUtils. toString ());

Var rs = xmlUtils. getNodesTextByName (['name', 'author']);
// Change the above dataType to array or the value is not json.
Document. getElementById ('xmloptest'). innerHTML + = '<br/> get the array of all text nodes:' + rs + '<br/> ';
// Ext json parsing tool Ext. encode is used to convert a json object to a string. Ext. decode converts a string in json format to a json object array.
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the JSON array of all text nodes:' + Ext. encode (rs) + '<br/> ';

Var root = xmlUtils. getRoot ();
XmlUtils. createNode ('Publish ', 'China power Publishing House', {id: 'id0001 '}, root );
XmlUtils. createCDATANode ('Publish ', 'China & Power Publishing House', {}, root );
// Set attributes
XmlUtils. setAttribute (root, 'testid', 'test ');
// Modify attributes
XmlUtils. setAttribute (root, 'testid', 'test10000000000 ');
Alert (xmlUtils. toString (root ));
XmlUtils. removeChild (xmlUtils. getNodesByXpath ('// root/publish') [0]);
Alert (xmlUtils. toString (root ));
Node = xmlUtils. getFirstChild ();
Document. getElementById ('xmloptest '). innerHTML + = '<br/> determine whether a subnode exists:' + xmlUtils. hasChildNodes (node) + '------ determines whether an attribute exists:'; // + xmlUtils. hasAttributes (node) + '<br/> ';
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the first node of the node:' + xmlUtils. getTagName (node) + "---" + xmlUtils. getText (node) + '======= node type:' + xmlUtils. getNodeType (node) + '<br/> ';
Node = xmlUtils. getNextNode (node );
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the next node of the first node of the node:' + xmlUtils. getTagName (node) + "---" + xmlUtils. getText (node) + '<br/> ';
Node = xmlUtils. getLastChild ();
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the last node of the node:' + xmlUtils. getTagName (node) + "---" + xmlUtils. getText (node) + '<br/> ';
Node = xmlUtils. getpreviusnode (node );
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the last node of the node:' + xmlUtils. getTagName (node) + "---" + xmlUtils. getText (node) + '<br/> ';
Node = xmlUtils. getParentNode (node );
Document. getElementById ('xmloptest'). innerHTML + = '<br/> get the parent node of the node:' + xmlUtils. toString (node) + '<br/> ';
Var nodes = xmlUtils. getChildNodes ();
Document. getElementById ('xmloptest'). innerHTML + = '<br/> obtain all the subnodes of the node:' + xmlUtils. toString (nodes) + '<br/> ';

Node = xmlUtils. getNodesByXpath ('// root/book/name', 2 );
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the node name and Text Value Based on xPath:' + xmlUtils. getTagName (node) + "---" + xmlUtils. getText (node) + '<br/> ';
Node = xmlUtils. getNodesByXpath ('// root/book/author ');
Document. getElementById ('xmloptest '). innerHTML + = '<br/> get the node name and Text Value Based on xPath:' + xmlUtils. getTagName (node [0]) + "---" + xmlUtils. getText (node [0]) + '<br/> ';

// Get the modified text node
Node = xmlUtils. getNodesByXpath ('// root/publish', 1 );
Node = xmlUtils. getFirstChild (node );
Document. getElementById ('xmloptest'). innerHTML + = '<br/> node text before modifying the text value:' + xmlUtils. getText (node );
XmlUtils. setText (node, "Travel Notes ");
Document. getElementById ('xmloptest'). innerHTML + = '----- modify the text value and then the node text:' + xmlUtils. getText (node );
XmlUtils. appendText (node, "test ");
Document. getElementById ('xmloptest'). innerHTML + = '----- node text after appending the text value:' + xmlUtils. getText (node) + "<br/> ";

// --> </Script>
</Html>

All the above files have been uploaded and are under review. After the review is passed, I will send them here.

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.