11

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 Answers 4

9

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

2
2

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.

1

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

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.

2
  • i am getting data of the google map, and need to store in xml file, and from the xml file i need to create map based on xml element..
    – Avinash
    Jul 28, 2009 at 7:00
  • 1
    Okay, I guess that means you're running in the browser (though it isn't necessarily so). And when you store the XML file, where do you want to store it? (In the file system of the computer where the browser is running? At the server where the page was served from?) Jul 28, 2009 at 7:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.