拥有如下所示的XML字符串:
<stages>
<params/>
<test description=""/>
</stages>
我想在<test desc.../>
代码之后或在阶段结束之前添加以下XML字符串,即</stages>
<stage id="myId" level="1">
以及所有后续阶段。
添加后应该
<stages>
<params/>
<test description=""/>
<stage id="myId" level="1"/>
<stage id=.../>
...
</stages>
我正在尝试做这样的事情:
var stageNode = document.createTextNode(
"<stage id=\"myId\" level=\"1\">")
);
var root = document.getElementsByTagName("test").parentNode;
console.log(document.getElementsByTagName("test")); //<-- giving [] in console log and root is undefined; though the element is there
var stages = root.getElementsByTagName("stage");
root.insertBefore(stageNode,stages.nextSibling);
我如何在JavaScript或JQuery中执行此操作?
使用DocumentBuilder或DocumentBuilderFactory给了我&#34;意外的标识符&#34;错误。有没有更简单的方法来使用Javascript中的文档构建器(如在Java中)?
答案 0 :(得分:0)
使用jQuery可能看起来像这样:
function addStage(xmlDocument, stageElement){
var parent = $(xmlDocument).find("test").parent(); //picks <test>'s parent
parent.append(stageElement); //appends stageElement to parent
}
var xmlString = '<stages><params/><test description=""/></stages>'; //your XML string
var xmlDocument = $.parseXML(xmlString); //parses your XML string and returns XML document
$("#addStage").click(function(){
var id = $("#stageId").val();
var stageElement = $("<stage id=\"" + id + "\"></stage>"); //creates new element
addStage(xmlDocument, stageElement);
console.log(xmlDocument);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Stage ID: <input type="text" id="stageId" /> <input type="button" id="addStage" value="Add stage" />
&#13;
打开浏览器的控制台以查看结果。
答案 1 :(得分:0)
使用普通旧JavaScript:
var text = "<stages><params/><test description=\"\"/></stages>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text,"text/xml");
var newNode = xmlDoc.createElement("stage");
newNode.setAttribute("id", "myId");
newNode.setAttribute("level", "1");
xmlDoc.documentElement.appendChild(newNode);
newNode = xmlDoc.createElement("stage");
newNode.setAttribute("id", "myId2");
newNode.setAttribute("level", "2");
xmlDoc.documentElement.appendChild(newNode);
console.log(new XMLSerializer().serializeToString(xmlDoc.documentElement));
有关在特定位置添加节点的参考,请参阅XML DOM Add Nodes