create and modify xml file using javascript

后端 未结 4 1634
故里飘歌
故里飘歌 2020-12-03 21:55

How do i create new xml file and also modify any xml file means add more nodes in xml file using javascript.?

Thanks in advance...

相关标签:
4条回答
  • 2020-12-03 22:25

    What context is the file running in, and where are you going to save the new XML data?

    (The usual context is the browser, in which case you're basically able to display it or post it back to the server.)

    But if you're writing a script that would run outside the browser, it depends.

    0 讨论(0)
  • 2020-12-03 22:28

    In IE you can manipulate XML using an ActiveX.
    There is also a built in object for FF and other W3C complient browsers.
    I recommend you to take a look at this article.

    0 讨论(0)
  • 2020-12-03 22:28

    I've created two functions as follows:

    function loadXMLDoc(filename){
      if (window.XMLHttpRequest){
          xhttp=new XMLHttpRequest();
      }
      else {
      xhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE 5-6
      }
      xhttp.open("GET",filename,false);
      xhttp.send();
      return xhttp.responseXML;
    }
    

    And, to write the XML into a local file call the following function.

    function writeXML() 
        {
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            var fso = new ActiveXObject("Scripting.FileSystemObject");
            var FILENAME="D:/YourXMLName/xml";
            var file = fso.CreateTextFile(FILENAME, true);
            file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
            file.WriteLine('<PersonInfo>\n');
            file.WriteLine('></Person>\n');
            } 
            file.WriteLine('</PersonInfo>\n');
            file.Close();
        } 
    

    I hope this helps, or else you can try Ariel Flesler's XMLWriter for creating XML in memory.

    0 讨论(0)
  • 2020-12-03 22:36

    I've found Ariel Flesler's XMLWriter constructor function to be a good start for creating XML from scratch, take a look at this

    http://flesler.blogspot.com/2008/03/xmlwriter-for-javascript.html

    Example

    function test(){    
       var v = new  XMLWriter();
       v.writeStartDocument(true);
       v.writeElementString('test','Hello World');
       v.writeAttributeString('foo','bar');
       v.writeEndDocument();
       console.log( v.flush() );
    }
    

    Result

    <?xml version="1.0" encoding="ISO-8859-1" standalone="true" ?>
    <test foo="bar">Hello World</test>
    

    One caveat to keep in mind is that it doesn't escape strings.

    See also Libraries to write xml with JavaScript

    0 讨论(0)
提交回复
热议问题