Xmlutils JS operation XML Tool class _javascript skills

Source: Internet
Author: User
Tags cdata eval gettext processing instruction tagname xpath

The demo uses a bit of ExtJS, mainly to print out the JSON array.
JS Code (XMLUTILS.JS):

Copy Code code as follows:

/**/
function Xmlutils (config) {
/* Define private properties * *
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 XML file, parameters:
* @param {string} Xmlpath: The loaded XML file path;
* @return {Object} true to load; false load failed
*/
Loadxml:function (Xmlpath) {
try {
This.xmlDoc.async = false;
This.xmlDoc.load (Xmlpath);
This.xmlpath = Xmlpath;
return true;
catch (e) {
return false;
}
},

/**
* Load 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");
}
},

/**
* To determine whether a node has child nodes
* @param {Object} node
* @return {Object} has child nodes returns True, otherwise returns false
*/
Haschildnodes:function (node) {
return Node.haschildnodes ();
},

/**
* To determine whether a node has attributes
* @param {Object} node
* @return {Object} returns True if it has properties, otherwise returns false
*/
Hasattributes:function (node) {
Return (node.attributes.length > 0)? True:false;
},

/**
* Determines whether a node is a text node, including a text node with a CDATA section
* @param {Object} node
* @return {Object} is a text node returns TRUE, otherwise returns false
*/
Istextnode:function (node) {
var type = this.getnodetype (node);
return (Type = = 3 | | | type = = 4)? True:false;
},

/**
* Return root node
* @return {Object} root node
*/
Getroot:function () {
return this.xmlDoc.documentElement;
},

/**
* Returns the first child node of the node, without parameters, returns the first child node of the root node
* @param {Object} node
* @return The first child node of the {Object} node
*/
Getfirstchild:function (node) {
Return node? Node.firstChild:this.getRoot (). FirstChild;
},

/**
* Returns the last child node of the node, without parameters, returns the first child node of the root node
* @param {Object} node
* @return The last child node of the {Object} node
*/
Getlastchild:function (node) {
Return node? Node.lastChild:this.getRoot (). LastChild;
},

/**
* Returns the node's next node, with no parameters returning the first child node of the root node
* @param {Object} node
* @return The next node of the {Object} node
*/
Getnextnode:function (node) {
Return node? Node.nextSibling:null;
},

/**
* Returns the previous node of the node, with no parameters returning the first child node of the root node
* @param {Object} node
* @return The previous node of the {Object} node
*/
Getpreviousnode:function (node) {
Return node? Node.previousSibling:null;
},

/**
* Returns the child nodes of the node and returns null without arguments
* @param {Object} node
* @return {Object} node all child nodes
*/
Getchildnodes:function (node) {
Return (node && this.haschildnodes (node))? Node.childNodes:null;
},

/**
* Returns the parent node of the node and returns null without arguments
* @param {Object} node
* @return {Object} node parent node
*/
Getparentnode:function (node) {
Return node? Node.parentNode:null;
},

/**
* Returns the node array text value according to the section name, Parameters:
* @param {string or object} nodename: node name;
* @return {Object} node has an array of returned nodes, and null if the node does not exist.
*/
Getnodestextbyname:function (nodenames) {
Return nodenames? (This.datatype = = ' json ' This.getjsonnodestextbyname (nodenames): This.getarrynodestextbyname (nodeNames)): null;
},

/**
* Return node normal array literal value according to section name, parameter:
* @param {string or object} nodename: node name;
* @return {Object} node has a normal array of return nodes.
*/
Getarrynodestextbyname:function (nodenames) {
var rs = [];
return 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;
},

/**
* Returns the node JSON array literal value according to the section name, Parameters:
* @param {string or object} nodename: node name;
* @return {Object} node has a return node JSON array, the node does not exist, returns NULL.
*/
Getjsonnodestextbyname:function (nodenames) {
var rs = null;
Returns 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;
},

/**
* According to the node properties to get the node, parameters:
* @param {String} key: Property name, default is ID
* @param {String} Value: Property value
* @return An array of node {String} matches the criteria.
*/
Getnodesbyattribute:function (key, value) {
Key = key? Key: ' ID ';
Value = value? Value: ';
Return ID? This.xmlDoc.getElementById (ID): null;
},

/**
* According to the section name to get the node, parameters:
* @param {string} tagName: node name
* @return {string} The node or array of nodes that specifies the name and location of the node.
*/
Getnodesbytagname:function (tagName) {
Return tagName? This.xmlDoc.getElementsByTagName (tagName): null;
},

/**
* Returns index node based on node path, parameter:
* @param {string} XPath: Node path
* @param {number}index: The location to index, empty or 0 returns all the found nodes.
* @return {string} The node or array of nodes that specifies the name and location of the node.
*/
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: Nodes
* @return {String} node text, empty to return null
*/
Gettext:function (node) {
Return node? Node.text:null;
},

/**
* Get the specified node name, parameters:
* @param {Object} node: Nodes
* @return {string} node name, NULL to return
*/
Gettagname:function (node) {
Return node? Node.nodeName:null;
},

/**
* Return node type, parameters:
* @param {Object} node: Nodes
* @return {string} node type, NULL to return nulls
* 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 nodes, Parameters:
* @param {string} nodename: node name, required
* @param {string} Text: node literal, nullable
* @param {Object} attributes: Property value-json Array, nullable, example: {id: ' id001 ', Name: ' name001 '}
* @param {Object} node: To increase the nodes of the child nodes, NULL to return the newly created node
* @param {Boolean} CDATA: Whether to generate a node with a CDATA section, true: Build, false: Do not generate
* @return the node created by {Object}, and returns null if there is an exception
*/
Createnode:function (nodename, text, attributes, node, CDATA) {
if (This.isie) {
Creating Child contacts
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 properties
for (var i in attributes) {
This.createattribute (Childnode,i,attributes[i]);
};

Return node? Node.appendchild (Childnode): Childnode;
} else {
Alert (' FF create node to say again. ');
return null;
}
},

/**
* Create nodes with CDATA sections, parameters:
* @param {string} nodename: node name, required
* @param {string} Text: node literal, nullable
* @param {Object} attributes: Property value-json Array, nullable, example: {id: ' id001 ', Name: ' name001 '}
* @param {Object} node: To increase the nodes of the child nodes, NULL to return the newly created node
*/
Createcdatanode:function (nodename, text, attributes, node) {
This.createnode (nodename, text, attributes, node, true);
},

/**
* Create node properties, Parameters:
* @param {Object} node: nodes, required
* @param {String} key: property name, required
* @param {Object} Value: Property value, required
* @param {Object} node: Returning nodes to new properties
* @return {Object} to increase the properties of the node, there are exceptions to return null
*/
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 create node to say again. ');
return node;
}
return null;
},

/**
* Add nodes to the root node, parameters:
* @param {Object} node: Nodes
* @return {Object} returns null if there is an exception
*/
Addnodetoroot:function (node) {
if (!node) return null;
This.getroot (). appendchild (node);
return node;
},

/**
* Add nodes to the other node, parameters:
* @param {Object} node: Nodes
*/
Addnode:function (Node,childnode) {
Return (node && childnode)? Node.appendchild (Childnode): false;
},

/**
* Remove the node itself from the parent node, parameters:
* @param {Object} NewNode: the node to replace
* @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 itself from the parent node, parameters:
* @param {Object} node: nodes to remove
*/
Removechild:function (node) {
if (!node | |!node.parentnode) return;
Node.parentNode.removeChild (node);
},

/**
* Remove all child nodes of the 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 node property value, no existing new, parameter:
* @param {Object} node: nodes to set
* @param {String} key: Property name to set
* @param {String} Value: Property value to set
*/
Setattribute:function (node, key, value) {
This.createattribute (node, key, value);
},

/**
* Set text for text nodes, parameters:
* @param {Object} node: nodes to set
* @param {String} text: Texts to set
*/
Settext:function (node, text) {
if (This.istextnode (node)) Node.text = text;
},

/**
* Append text to the text node, parameters:
* @param {Object} node: nodes to set
* @param {String} text: Texts to set
*/
Appendtext:function (node, text) {
if (This.istextnode (node)) node.appenddata (text);
},


/**
* Output XML, NULL to output root node text, parameters:
* @param {Object} node: nodes to output
*/
Tostring:function (node) {
node = node? Node:this.xmlDoc.documentElement;
if (typeof node = = ' string ') return node;
Return This.isie? Node.xml:new XMLSerializer (). serializetostring (node);
}
}

Tested XML file (Book.xml):
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<root>
<book>
<name> journey to the westward </name>
<author> en </author>
</book>
<book>
<name> dream of Red mansions </name>
<author> Cao Xueqin </author>
</book>
<book>
<name> Kingdoms </name>
<author>
<name> Nai </name>
<sex> male </sex>
</author>
</book>
<book>
<name> Marsh </name>
<author> Guanzhong </author>
</book>
</root>

HTML code (test.html):
Copy Code code as follows:

<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>
<body>
<div id= ' xmloptest ' ></div>
</body>
<script type= "Text/javascript" ><!--
/**
* Config parameter: Xmlpath file address, datatype data format-json or Arry, the default is array.
*/
var xmlutils = new Xmlutils ({xmlpath: "Book.xml", DataType: ' json '});
Alert (xmlutils.tostring ());

var rs = xmlutils.getnodestextbyname ([' Name ', ' author ']);
To change the above datatype to array or not to JSON, you can get a value here.
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get an array of all the text nodes: ' +rs + ' <br/> ';
This method uses the EXT JSON parsing tool Ext.encode to convert a JSON object to a string. Ext.decode, instead, converts a string in JSON format to an array of JSON objects
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get all the text nodes in the JSON array: ' +ext.encode (RS) + ' <br/> ';

var root = Xmlutils.getroot ();
Xmlutils.createnode (' Publish ', ' China Power Press ', {ID: ' id0001 '},root);
Xmlutils.createcdatanode (' Publish ', ' China & Power Press ', {},root);
Setting properties
Xmlutils.setattribute (Root, ' testid ', ' test ');
modifying properties
Xmlutils.setattribute (Root, ' testid ', ' test0000000000 ');
Alert (xmlutils.tostring (root));
Xmlutils.removechild (Xmlutils.getnodesbyxpath ('//root/publish ') [0]);
Alert (xmlutils.tostring (root));
node = Xmlutils.getfirstchild ();
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> determine if there are subnodes: ' +xmlutils.haschildnodes node + '------ Determine whether there are attributes: ';//+ xmlutils.hasattributes (node) + ' <br/> ';
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get node's first node: ' +xmlutils.gettagname (node) + '---' + Xmlutils.gettext (node) + ' ======== nodes type: ' + xmlutils.getnodetype (node) + ' <br/> ';
node = xmlutils.getnextnode (node);
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get node's first node next node: ' +xmlutils.gettagname (node) + '---' + Xmlutils.gettext (node) + ' <br/> ';
node = Xmlutils.getlastchild ();
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get node's last node: ' +xmlutils.gettagname (node) + '---' + Xmlutils.gettext (node) + ' <br/> ';
node = xmlutils.getpreviousnode (node);
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get node last node: ' +xmlutils.gettagname (node) + '---' + Xmlutils.gettext (node) + ' <br/> ';
node = xmlutils.getparentnode (node);
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get node's parent node: ' + xmlutils.tostring (node) + ' <br/> ';
var nodes = Xmlutils.getchildnodes ();
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get all child nodes of node: ' +xmlutils.tostring (nodes) + ' <br/> ';

node = Xmlutils.getnodesbyxpath ('//root/book/name ', 2);
document.getElementById (' Xmloptest '). InnerHTML + = ' <br/> get 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 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/> Modify text value before node text: ' +xmlutils.gettext (node);
Xmlutils.settext (node, "Journey to the Back");
document.getElementById (' Xmloptest '). InnerHTML + = '-----To modify the text value after the node text: ' +xmlutils.gettext;
Xmlutils.appendtext (node, "test");
document.getElementById (' Xmloptest '). InnerHTML + = '-----Append text value after node text: ' +xmlutils.gettext (node) + <br/>;

--></script>

The above files are uploaded, is under review, and so the audit passed I will send to 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.