我想从用户输入向XML文件添加新元素。 我尝试了很多方法,但没有一个能为我工作:(
如何使用JavaScript或jQuery将新节点/元素/项添加到现有本地XML文件中?
这是我目前的状态:
function addElement() {
var xml;
if (window.activexobject) {
xml = new activexobject("microsoft.xmlhttp");
} else {
xml = new xmlhttprequest();
}
xml.onreadystatechange = function () {
if (xml.readystate == 4 && xml.status == 200) {
var resp = xml.responsexml;
var user = xml.responsexml.createelement("User");
var name = xml.responsexml.createelement("name");
name.appendchild(xml.responsexml.createtextnode("sof_user"));
var admin = xml.responsexml.createelement("admin");
admin.appendchild(xml.responsexml.createtextnode("false"));
user.appendchild(name);
user.appendchild(admin);
xml.responsexml.documentelement.appendchild(user);
}
}
xml.open("get", "users.xml", true);
xml.send(null);
}
XML应如下所示:
<Users>
<User>
<name>testuser</name>
<admin>true</admin>
</User>
<User>
<name>sof_user</name>
<admin>false</admin>
</User>
....
</Users>
答案 0 :(得分:1)
您应该能够像这样构建XML:
usersNode = document.createElement("Users");
userNode = document.createElement("User");
nameNode = document.createElement("name");
nameNode.innerText = "testuser";
adminNode = document.createElement("admin");
adminNode.innerText = "true";
userNode.appendChild(nameNode);
userNode.appendChild(adminNode);
usersNode.appendChild(userNode);
userNode = document.createElement("User");
nameNode = document.createElement("name");
nameNode.innerText = "sof_user";
adminNode = document.createElement("admin");
adminNode.innerText = "false";
userNode.appendChild(nameNode);
userNode.appendChild(adminNode);
usersNode.appendChild(userNode);
console.log(usersNode.innerHTML);
我认为应该给你你想要的东西。