XmlUtilsJS operating XML tool_javascript skills

Source: Internet
Author: User
Tags processing instruction
Xml operations are often used. Java contains dom, dom4j, and other tool classes, but Javascript does not. So I wrote one myself. Currently, it is counted as the first version. There must be many improvements. If you need them, you can leave a message or comment on bugs and areas that require improvement. The demo uses extjs to print the json array.
Js code (XmlUtils. js ):

The 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; itry {
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 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 ):

The Code is as follows:





Travel to the west
Wu chengen


Dream of Red Mansions
Cao Xueqin


Romance of Three Kingdoms

Shi nai
Male



Water Margin
Luo Guanzhong



Html code (test.html ):

The Code is as follows:





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.