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...

Avinash
  • 585
  • 3
  • 9
  • 17

4 Answers4

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

Community
  • 1
  • 1
Alex Nolasco
  • 18,750
  • 9
  • 86
  • 81
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.

Wahid Kadwaikar
  • 768
  • 7
  • 10
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.

the_drow
  • 18,571
  • 25
  • 126
  • 193
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.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • 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 '09 at 07: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?) – Daniel Earwicker Jul 28 '09 at 07:03