Home  >  Article  >  Web Front-end  >  XmlUtils JS operation XML tool class_javascript skills

XmlUtils JS operation XML tool class_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:45:231099browse

The demo uses some extjs stuff, mainly to print the json array.
js code(XmlUtils.js):

Copy code The code is as follows:

/**/
function XmlUtils (config) {
/*개인 속성 정의*/
this.isIE = !!(window.attachEvent && !window.opera);
this.init();
if(config) {
this.dataType = config.dataType == 'json' ? 'json' : '배열';
if(config.xmlPath) this.loadXml(config.xmlPath);
}
}
XmlUtils.prototype = {
xmlDoc : null,
xmlPath : null,
dataType : null,
/**
* 초기화
*/
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);
}
},

/**
* xml 파일 로드, 매개변수:
* @param {string} xmlPath: 로드된 xml 파일의 경로
* @return {Object} 일반 로드의 경우 true, 로드 실패의 경우 false
*/
loadXml : function (xmlPath) {
try {
this.xmlDoc.async = false;
this.xmlDoc.load(xmlPath);
this.xmlPath = xmlPath;
참을 반환합니다.
} catch (e) {
false를 반환;
}
},

/**
* XML 문자열 로드
* @param {Object} XMLString
*/
loadXmlString: function(xmlString) {
if (this.isIE) {
this.xmlDoc. loadXML(xmlString);
} else {
var parser = new DOMParser();
this.XMLDoc = 파서.parseFromString(xmlString, "text/xml");
}
},

/**
* 노드에 하위 노드가 있는지 확인
* @param {Object} node
* @return {Object} 하위 노드가 있으면 true를 반환하고, 그렇지 않으면 false를 반환
*/
hasChildNodes : function (노드) {
return node.hasChildNodes();
},

/**
* 노드에 속성이 있는지 확인
* @param {Object} 노드
* @return {Object} 속성이 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
*/
hasAttributes : function (node) {
return (node.attributes.length > 0) ? 사실 : 거짓;
},

/**
* CDATA 섹션이 있는 텍스트 노드를 포함하여 노드가 텍스트 노드인지 확인
* @param {Object} 노드
* @return {Object} 텍스트 노드인 경우 true를 반환하고, 그렇지 않은 경우 반환 거짓
*/
isTextNode : function(노드) {
var type = this.getNodeType(node);
반환(유형 == 3 || 유형 == 4) ? 사실 : 거짓;
},

/**
* 루트 노드 반환
* @return {Object} 루트 노드
*/
getRoot : function () {
return this.xmlDoc.documentElement;
},

/**
* 노드의 첫 번째 하위 노드를 반환합니다. 매개변수가 없는 경우 루트 노드의 첫 번째 하위 노드를 반환합니다.
* @param {Object} 노드
* @return {Object} 노드의 하위 노드
*/
getFirstChild : function (node) {
return node ? node.firstChild : this.getRoot().firstChild;
},

/**
* 노드의 마지막 자식 노드를 반환합니다. 매개변수가 없으면 루트 노드의 첫 번째 자식 노드를 반환합니다.
* @param {Object} 노드
* @return {Object} 마지막 자식 노드를 반환합니다. 노드의 노드
*/
getLastChild : function (노드) {
return node ? node.lastChild : this.getRoot().lastChild;
},

/**
* 노드의 다음 노드를 반환합니다. 매개 변수가 없는 경우 루트 노드의 첫 번째 자식 노드를 반환합니다.
* @param {Object} 노드
* @return {Object} 의 다음 노드를 반환합니다. 노드
*/
getNextNode : function (노드) {
return node ? node.nextSibling : null;
},

/**
* 해당 노드의 이전 노드를 반환합니다. 매개 변수가 없는 경우 루트 노드의 첫 번째 하위 노드를 반환합니다.
* @param {Object} 노드
* @return {Object} 이전 노드를 반환합니다. 노드
*/
getPreviousNode : function (노드) {
return node ? node.previousSibling : null;
},

/**
* 노드의 하위 노드를 반환하거나 매개변수가 없는 경우 null을 반환합니다.
* @param {Object} 노드
* @return {Object} 노드의 모든 하위 노드
*/
getChildNodes : function (노드) {
return (node ​​&& this.hasChildNodes(노드)) ? node.childNodes : null;
},

/**
* 노드의 상위 노드를 반환하거나 매개변수가 없는 경우 null을 반환합니다.
* @param {Object} 노드
* @return {Object} 노드의 상위 노드
*/
getParentNode : function (노드) {
return node ? node.parentNode : null;
},

/**
* 노드 이름, 매개변수에 따라 노드 배열 텍스트 값을 반환합니다.
* @param {string or object} nodeName: 노드 이름
* @return {object}는 노드가 다음과 같은 경우 노드 배열을 반환합니다. 노드가 존재하지 않으면 null을 반환합니다.
*/
getNodesTextByName : function (nodeNames) {
return nodeNames ? (this.dataType == 'json' ? this.getJsonNodesTextByName(nodeNames) : this.getArryNodesTextByName(nodeNames)) : null;
},

/**
* 根据节点name返回节点普通数组文本值,参数:
* @param {string或object} nodeName:节点name称;
* @return {객체} 节点存在返回节点普通数组。
*/
getArryNodesTextByName : function (nodeNames) {
var rs = [];
//返回普通数组格式
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 text value according to the node name, parameters:
* @param {string or object} nodeName: node name;
* @return {object} The node exists and returns the node JSON array; the node does not Returns null if exists.
*/
getJsonNodesTextByName : function (nodeNames) {
var rs = null;
//返回JSON数组格式
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 based on the node attributes, parameters:
* @param {String} key: attribute name, the default is id
* @param {String} value: attribute value
* @return {String } Array of nodes that meet the condition.
*/
getNodesByAttribute : function (key, value) {
key = key ? key : 'id';
value = value ? value : '';
return id ? this.xmlDoc.getElementById(id) : null;
},

/**
* Get the node based on the node name, parameters:
* @param {string} tagName: node name
* @return {string} Specifies the node name and position of the node or node array.
*/
getNodesByTagName : function (tagName) {
return tagName ? this.xmlDoc.getElementsByTagName(tagName) : null;
},

/**
* 根据节点路径返回第index个节点,参数:
* @param {string} xPath:节点路径
* @param {number}index:要索引的位置,为空或0则返回所有查找到的节点。
* @return {string} 指定节点名字的和位置的节点或节点数组。
*/
getNodesByXpath : function (xPath, index) {
if (!xPath) return null;
var 노드 = this.xmlDoc.selectNodes(xPath);
var len = 노드.길이;
if(!index || index > len || index < 0) return 노드;
for(var i=0; iif(i == index - 1) return 노드[i];
}
},

/**
* 지정된 노드 텍스트 가져오기, 매개변수:
* @param {object} 노드: 노드
* @return {string} 노드 텍스트, 비어 있으면 null 반환
*/
getText : function (node) {
return node ? 노드.텍스트: null;
},

/**
* 지정된 노드 이름, 매개변수 가져오기:
* @param {object} 노드: 노드
* @return {string} 노드 이름, 비어 있으면 null 반환
*/
getTagName : 함수(노드) {
return node ? node.nodeName : null;
},

/**
* 반환 노드 유형, 매개변수:
* @param {object} 노드:노드
* @return {string} 노드 유형, 비어 있으면 null 반환
* 1-요소
* 2-속성
* 3-텍스트
* 4-cdata
* 5-엔티티 참조
* 6-엔티티
* 7-pi(처리 명령)
* 8-코멘트
* 9-문서
* 10-문서 유형
* 11-문서 조각
* 12-표기
*/
getNodeType : function (노드) {
return node ? node.nodeType : null;
},

/**
* 노드 생성, 매개변수:
* @param {string} nodeName: 노드 이름, 필수
* @param {string} text: 노드 텍스트, 비어 있을 수 있음
* @param {Object } 속성: 속성 값 - JSON 배열, 비어 있을 수 있습니다. 예: {id:'id001',name:'name001'}
* @param {Object} 노드: 하위 노드를 추가할 노드, 비어 있으면 반환 새 노드
* @param {Boolean} cdata: CDATA 섹션으로 노드를 생성할지 여부, true: 생성됨, false: 생성되지 않음
* @return {Object} 생성된 노드, 예외가 있는 경우 null 반환
*/
createNode: function(nodeName, text, attribute, 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 attribute) {
this.createAttribute(childNode,i,attributes[i]);
};

노드 반환 ? node.appendChild(childNode) : childNode;
} else {
alert('FF创建节点再说.');
널을 반환합니다.
}
},

/**
* CDATA 섹션이 있는 노드 생성, 매개변수:
* @param {string} nodeName: 노드 이름, 필수
* @param {string} text: 노드 텍스트, 비어 있을 수 있음
* @ param {Object} 속성: 속성 값-JSON 배열, 비어 있을 수 있습니다. 예: {id:'id001',name:'name001'}
* @param {Object} 노드: 하위 노드를 추가할 노드, 비어 있으면 새로 생성된 노드를 반환합니다
*/
createCDATANode: function(nodeName, text, attribute, node) {
this.createNode(nodeName, text, 속성, 노드, true);
},

/**
* 노드 속성 생성, 매개변수:
* @param {Object} 노드: 노드, 필수
* @param {String} 키: 속성 이름, 필수
* @param {Object} 값: 속성 값, 필수
* @param {Object} 노드: 속성이 추가된 노드를 반환합니다.
* @return {Object} 속성이 추가된 노드, 예외가 있는 경우 null을 반환합니다.
*/
createAttribute: function(node, key, value) {
if (this.isIE) {
if(!key ) 반품;
var attr = this.xmlDoc.createAttribute(key);
attr.value = 값 ? 값 : "";
node.setAttributeNode(attr);
반환 노드;
} else {
alert('FF创建节点再说.');
반환 노드;
}
null을 반환합니다.
},

/**
* 루트 노드에 노드 추가, 매개변수:
* @param {Object} 노드: 노드
* @return {Object} 예외가 있는 경우 null을 반환
*/
addNodeToRoot: function(node) {
if(!node) return null;
this.getRoot().appendChild(노드);
반환 노드;
},

/**
* 노드를 다른 노드에 추가합니다. 매개변수:
* @param {Object} 노드: 노드
*/
addNode: function(node,childNode) {
return (node ​​&& childNode) ? node.appendChild(childNode) : 거짓;
},

/**
* 상위 노드에서 노드 자체를 제거합니다. 매개변수:
* @param {Object} newNode: 교체할 노드
* @param {Object} oldNode: 교체할 노드
*/
replaceChild: function(newNode, oldNode) {
var parentNode = oldNode.parentNode;
if(!newNode || !oldNode || !parentNode) return;
parentNode.replaceChild(newNode, oldNode);
},

/**
* 상위 노드에서 노드 자체를 제거합니다. 매개변수:
* @param {Object} 노드: 제거할 노드
*/
removeChild: function(node) {
if(!node || !node.parentNode) return;
node.parentNode.removeChild(노드);
},

/**
* 노드의 모든 하위 노드 제거, 매개변수:
* @param {Object} 노드: 상위 노드
*/
removeChildNodes: function(node) {
if (node ​​&& this.hasChildNodes(node)) {
var childNodes = node.childNodes;
for(var i = 0; i < childNodes.length; i ) {
node.removeChild(childNodes[0]);
}
}
},

/**
* 노드 속성 값을 설정합니다. 매개변수:
* @param {Object} 노드: 설정할 노드
* @param {String} 키: 설정할 속성 이름
* @param {String} value : 설정할 속성 값
*/
setAttribute: function(node, key, value) {
this.createAttribute(node, key, value);
},

/**
* 텍스트 노드의 텍스트 설정, 매개변수:
* @param {Object} 노드: 설정할 노드
* @param {String} 텍스트: 설정할 텍스트
*/
setText: function(node, text) {
if(this.isTextNode(node)) node.text = text;
},

/**
* 텍스트 노드 뒤에 텍스트 추가, 매개변수:
* @param {Object} 노드: 설정할 노드
* @param {String} 텍스트: 설정할 텍스트
*/
appendText: function(node, text) {
if(this.isTextNode(node)) node.appendData(text);
},


/**
* 출력 xml, 비어 있으면 루트 노드 텍스트가 출력됩니다. 매개변수:
* @param {Object} 노드: 출력할 노드
*/
toString: function(node) {
node = node ? 노드 : this.xmlDoc.documentElement;
if (노드 유형 == '문자열') return node;
이것을 반환하세요.isIE ? node.xml : new XMLSerializer().serializeToString(node);
}
}

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


<루트>
<책>
西游记
吴承恩

<책>
红楼梦
曹雪芹

<책>
삼국演义
<저자>
施耐庵



<책>
水浒传
罗贯中



html 코드(test.html):
复system代码 代码如下:




test xml






위 파일이 업로드되어 검토 중입니다. 승인되면 여기로 보내드리겠습니다.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn