XmlUtils JS操作XMLツールclass_javascriptスキル

WBOY
リリース: 2016-05-16 18:45:23
オリジナル
1104 人が閲覧しました

デモでは、主に json 配列を出力するために、いくつかの extjs のものを使用します。
js コード(XmlUtils.js):

コードをコピー コードは次のとおりです:

/**/
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; itry{
this.xmlDoc = new ActiveXObject(activexArr[i]);
}catch(e){}
}
} else {
this.xmlDoc = document.implementation.createDocument("", "", null);
}
},

/**
* Load xml file, parameters:
* @param {string} xmlPath: path of loaded xml file;
* @return {Object} true for normal loading; false for loading failure
*/
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");
}
},

/**
* Determine whether the node has child nodes
* @param {Object} node
* @return {Object} If there are child nodes, return true, otherwise return false
*/
hasChildNodes : function (node) {
return node.hasChildNodes();
},

/**
* Determine whether the node has attributes
* @param {Object} node
* @return {Object} If it has attributes, it returns true, otherwise it returns false
*/
hasAttributes : function (node) {
return (node.attributes.length > 0) ? true : false;
},

/**
* Determine whether the node is a text node, including text nodes with CDATA sections
* @param {Object} node
* @return {Object} If it is a text node, return true, otherwise return 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. If there is no parameter, returns the first child node of the root node.
* @param {Object} node
* @return {Object} The first child node of the node. Node
*/
getFirstChild : function (node) {
return node ? node.firstChild : this.getRoot().firstChild;
},

/**
* Returns the last child node of the node. If there is no parameter, returns the first child node of the root node
* @param {Object} node
* @return {Object} The last child node of the node
*/
getLastChild : function (node) {
return node ? node.lastChild : this.getRoot().lastChild;
},

/**
* Returns the next node of the node. If there is no parameter, returns the first child node 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 node. If there is no parameter, returns the first child node of the root node
* @param {Object} node
* @return {Object} The previous node of the node
*/
getPreviousNode : function (node) {
return node ? node.previousSibling : null;
},

/**
* Returns the child nodes of the node, or null if there is no parameter
* @param {Object} node
* @return {Object} All child nodes of the node
*/
getChildNodes : function (node) {
return (node && this.hasChildNodes(node)) ? node.childNodes : null;
},

/**
* Returns the parent node of the node, or null if there is no parameter
* @param {Object} node
* @return {Object} The parent node of the node
*/
getParentNode : function (node) {
return node ? node.parentNode : null;
},

/**
* Returns the node array text value according to the node name, parameters:
* @param {string or object} nodeName: node name;
* @return {object} returns the node array if the node exists; if the node does not exist, Return null.
*/
getNodesTextByName : function (nodeNames) {
return nodeNames ? (this.dataType == 'json' ? this.getJsonNodesTextByName(nodeNames) : this.getArryNodesTextByName(nodeNames)) : null;
},

/**
* 根据节点名返回节点普通数组文本值,参数:
* @param {string或object} nodeName:节点名称;
* @return {object} 节点存在返回节点普通数组。
*/
getArryNodesTextByName : function (nodeNames) {
var rs = [];
//普通数组格式を返します
switch (typeof(nodeNames)) {
case 'string':
var nodes = this.getNodesByTagName(nodeNames);
for (var i = 0; i rs.push(nodes[i].text);
}
休憩;
case 'object':
var subRs;
var ノード;
for (var i = 0; i nodes = this.getNodesByTagName(nodeNames[i]);
subRs = [];
for (var j = 0; j subRs.push(nodes[j].text);
}
rs.push(subRs);
}
休憩;
}
rs を返します。
},

/**
* ノード名、パラメーターに従ってノードの JSON 配列テキスト値を返します。
* @param {文字列またはオブジェクト} nodeName: ノード名
* @return {object} ノードが存在し、ノード JSON 配列。ノードが存在する場合は null を返しません。
*/
getJsonNodesTextByName : function (nodeNames) {
var rs = null;
//戻りJSON数组格式
switch (typeof(nodeNames)) {
case 'string':
eval('rs = {' nodeNames ':[]}');
var ノード = this.getNodesByTagName(nodeNames);
for (var i = 0; i eval('rs.'nodeNames '.push({'nodeNames i ':nodes[i].text})') ;
}
休憩;
ケース 'オブジェクト':
rs = {};
var ノード;
for (var i = 0; i eval('rs.' nodeNames[i] '=[]');
nodes = this.getNodesByTagName(nodeNames[i]);
for (var j = 0; j eval('rs.' ノード名[i] '.push({' ノード名[i] j ': ノード[j] 。文章})');
}
}
休憩;
}
rs を返します。
},

/**
* ノード属性、パラメーターに基づいてノードを取得します:
* @param {String} キー: 属性名、デフォルトは ID
* @param {String} 値: 属性値
* @return {String } 条件を満たすノードの配列。
*/
getNodesByAttribute : function (key, value) {
key = key ?キー: 'id';
値 = 値 ?価値 : '';
IDを返しますか? this.xmlDoc.getElementById(id) : null;
},

/**
* ノード名に基づいてノードを取得します。パラメーター:
* @param {string} tagName: ノード名
* @return {string} ノード名とノードまたはノード配列の位置を指定します。
*/
getNodesByTagName : function (tagName) {
return tagName ? this.xmlDoc.getElementsByTagName(タグ名) : null;
},

/**
* に基づいて节点路径を返す第インデックス个节点、パラメータ:
* @param {string} xPath:节点路径
* @param {number
* @return {string} は、ポイント名と位置のポイントまたはカウント数を指定します。
*/
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; iif(i == index - 1) return nodes[i];
}
},

/**
* Get the specified node text, parameters:
* @param {object} node: node
* @return {string} node text, if it is empty, return null
*/
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 empty, return null
*/
getTagName : function (node) {
return node ? node.nodeName : null;
},

/**
* Return node type, parameters:
* @param {object} node:Node
* @return {string} node type, if empty, return null
* 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 node, parameters:
* @param {string} nodeName: node name, required
* @param {string} text: node text, can be empty
* @param {Object } attributes: attribute value - JSON array, can be empty, for example: {id:'id001',name:'name001'}
* @param {Object} node: node to add child nodes, return if empty New node
* @param {Boolean} cdata: Whether to generate nodes with CDATA sections, true: generated, false: not generated
* @return {Object} The created node, if there is an exception, return null
*/
createNode: function(nodeName, text, attributes, node, cdata) {
if (this.isIE) {
//创建子接点
var childNode = this.xmlDoc.createElement(nodeName);
//创建文本节点
var textNode = cdata == true ? this.xmlDoc.createCDATASection(text) : this.xmlDoc.createTextNode(text);
childNode.appendChild(textNode);
//添加属性
for (var i in attributes) {
this.createAttribute(childNode,i,attributes[i]);
};

return node ? node.appendChild(childNode) : childNode;
} else {
alert('FF创建节点再说.');
return null;
}
},

/**
* Create a node with CDATA section, parameters:
* @param {string} nodeName: node name, required
* @param {string} text: node text, can be empty
* @param {Object} attributes: attribute value-JSON array, can be empty, for example: {id:'id001',name:'name001'}
* @param {Object} node: the node to add child nodes , if empty, return the newly created node
*/
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: Returns the node with the added attribute
* @return {Object} The node with the added attribute, returns null if there is an exception
*/
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创建节点再说.');
return node;
}
return null;
},

/**
* Add the node to the root node, parameters:
* @param {Object} node: node
* @return {Object} If there is an exception, return null
*/
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 itself 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 itself 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 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 the node attribute value. If it does not exist, create a new one. Parameters:
* @param {Object} node: the node to be set
* @param {String} key: the attribute name 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: the node to be set
* @param {String} text: the text to be set
*/
setText: function(node, text) {
if(this.isTextNode(node)) node.text = text;
},

/**
* Append text after the text node, parameters:
* @param {Object} node: the node to be set
* @param {String} text: the text to be set
*/
appendText: function(node, text) {
if(this.isTextNode(node)) node.appendData(text);
},


/**
* Output xml, if it is empty, the root node text will be output. Parameters:
* @param {Object} node: the node to be 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);
}
}

测试的xml文件(book.xml):
复制代码 代码如下:




西游记
吴承恩


红楼梦
曹雪芹


三国演义

施耐庵




水浒传
罗贯中



html code (test.html):
复制代码 代码如下:





test xml








The above files have been uploaded and are being reviewed. I will send them here when they are approved.
関連ラベル:
js
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!