Create XML in Javascript

后端 未结 7 758
慢半拍i
慢半拍i 2020-11-28 07:16

I\'m wondering, is it possible to create an XML file with some data in Javascript? I have the data stored in variables.

I\'ve googled around a bit and it doesn\'t see

7条回答
  •  庸人自扰
    2020-11-28 07:38

    Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.

    JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:

    1. Creating a new XML DOM object

    var xmlDoc = document.implementation.createDocument(null, "books");
    

    The first argument can contain the namespace URI of the document to be created, if the document belongs to one.

    Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument

    2. Fetching an XML file with XMLHttpRequest

    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
    
        var xmlDoc = xhttp.responseXML; //important to use responseXML here
    }
    xhttp.open("GET", "books.xml", true);
    xhttp.send();
    

    3. Parsing a string containing serialized XML

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

    When you have obtained an XML DOM object, you can use methods to manipulate it like

    var node = xmlDoc.createElement("heyHo");
    var elements = xmlDoc.getElementsByTagName("root");
    elements[0].appendChild(node);
    

    For a full reference, see http://www.w3schools.com/xml/dom_intro.asp

    Note: It is important, that you don't use the methods provided by the document namespace, i. e.

    var node = document.createElement("Item");
    

    This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.

    You can serialize XML DOM objects like this:

    var serializer = new XMLSerializer();
    var xmlString = serializer.serializeToString(xmlDoc);
    

提交回复
热议问题