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 seem like it's talked about much. I thought I could use XMLWriter
such as this:
var XML = new XMLWriter(); XML.BeginNode ("testing"); XML.Node("testingOne"); XML.Node("TestingTwo"); XML.Node("TestingThree"); XML.EndNode();
as stated in this tutorial: EHow Tutorial
However, when I execute this code, I get the following error:
ReferenceError: XMLWriter is not defined
How can I solve this error?
With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.
XML organizes and structures data for the web. In many ways, it is like a database; in others, it is like a text file storing data. However, XML looks a lot like an HTML page as well, but with no built-in formatting tags. XML tags only order data. All of the tag names in XML are ones provided by the designer.
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 = "<root></root>"; 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With