使用javascript xml解析器在XMLnode中插入属性

时间:2016-09-20 20:02:01

标签: javascript xml

这是存储在变量" xml"。

中的xml字符串
<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:extratask="http://extratask" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn">
<bpmn:process id="Process_1" isExecutable="false">
  <bpmn:task id="Task_15xgmrn" name="Select1Select5" extratask:entity="Select1" extratask:action="Select5" />
<bpmn:task id="Task_0ditp3t" name="Select2Select6" extratask:entity="Select2" extratask:action="Select6" />
<bpmn:task id="Task_0p68hrl" name="Select3Select6" extratask:entity="Select3" extratask:action="Select6" />
</bpmn:process>
</bpmn:definitions>

到目前为止,我刚刚尝试读取节点&#34; bpmn:task&#34;使用此代码进入控制台但获取空白数组。

if(window.DOMParser){
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(xml, "text/xml");
}else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(xml);
}
console.log(xmlDoc.getElementsByTagName("bpmn:task"));

请有人让我明白我哪里出错了,另一件事是我想在&#34; bpmn:task&#34;中插入一些属性。标签

1 个答案:

答案 0 :(得分:0)

属性xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL"表示XML的自定义命名空间,这意味着您必须使用带有命名空间的getElementsByTagNameNS()来获取标记

xmlDoc.getElementsByTagNameNS("http://www.omg.org/spec/BPMN/20100524/MODEL","task")

&#13;
&#13;
var xml = '<?xml version="1.0" encoding="UTF-8"?><bpmn:definitions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" xmlns:extratask="http://extratask" id="Definitions_1" targetNamespace="http://bpmn.io/schema/bpmn"><bpmn:process id="Process_1" isExecutable="false"><bpmn:task id="Task_15xgmrn" name="Select1Select5" extratask:entity="Select1" extratask:action="Select5" /><bpmn:task id="Task_0ditp3t" name="Select2Select6" extratask:entity="Select2" extratask:action="Select6" /><bpmn:task id="Task_0p68hrl" name="Select3Select6" extratask:entity="Select3" extratask:action="Select6" /></bpmn:process></bpmn:definitions>';

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml, "text/xml");

console.log(xmlDoc.getElementsByTagNameNS("http://www.omg.org/spec/BPMN/20100524/MODEL","task"));
&#13;
&#13;
&#13;