Add new node to local XML file using JS or jQuery

I would like to add new elements to an XML file from user input. I tried many possible ways, but none of them worked for me :(

How can I add a new node / element / item to an existing local XML file using JavaScript or jQuery?

This is my current state:

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 should look like this:

<Users>
    <User>
        <name>testuser</name>
        <admin>true</admin>
    </User>
    <User>
        <name>sof_user</name>
        <admin>false</admin>
    </User>
    ....
</Users>

      

+3


source to share


1 answer


You should create your XML something like this:

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);

      



I think this should give you what you want.

+1


source







All Articles