简体   繁体   中英

Write an XML file in javascript

I need to write an XML file using Java script. The code I have been able to come up with so far is as below.

function loadXMLDoc(dname) {    
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
} 

function GenerateDocument() {
    var xmlDoc = loadXMLDoc("XMLFile.xml");

    newelm = xmlDoc.createElement("Company");
    newAtt = xmlDoc.createAttribute("Name");
    newAtt.nodeValue = "ABC";

    //newelm.setAttributeNode(newAtt);
    x = xmlDoc.getElementsByTagName("Companies");
    x.appendChild(newelm);
}

I can see the elements and attributed in xmlDoc object But I am not able to add child elements and attribues to the XML file. Any help is appreciated.

Thanks

As xato mentioned, you won't be able to modify the actual file that you loaded via that AJAX call. JavaScript inside a browser does not normally allow you to write files. You could however write the XML out to the browser once you finished modifying it, or send it back to the server to be written by server-side script.

Edit: Once you have finished manipulating your XML document, you can use the XMLSerializer to write it out as text to the browser or store it in a string.

var s = new XMLSerializer();
document.write(s.serializeToString(xmlDoc));

Source: https://developer.mozilla.org/en/XMLSerializer

if the xml is large u can consider using a SAX parser !

through JS
you can also use zXml.js which will take care of the cross browser dependencies and provide functions and properties similar to IE

you can load the XML using

xmldom = new ActiveXObject("MSXML2.DOMDocument.6.0");

//loading an xml file is async by default
//use xmldom.async = false; to load sync

xmldom.load("addr.xml"); //give the xml file as an input 

//check if xml has errors
if(xmldom.parseError.errorCode)
{
    alert(xmldom.parseError.reason);
    return;
}
else //successfully loaded xml
{
     e = document.createElement("test");
     e.setAttribute("abc","xyz"); 

     document.getElementById("id").appendChild(e);
}

why dont you use ?

      xmlDoc.setAttribute("Name","abc");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM