- How To Create XML File Using Nodejs xmlbuilder2
- How To Create A New XML File
- The target XML file
- How To Install xmlbuilder2
- How To Install xmlbuilder2
- Generate Xml File
- Write and Save XML File
- The full Source:
- Output:
- how to save xml files using Javascript?
- Answers
- Javascript save xml file
- Asked by:
- Question
- All replies
- Dev centers
- Learning resources
- Community
- Support
- Programs
How To Create XML File Using Nodejs xmlbuilder2
This tutorial help to create an XML file using nodejs. We’ll use the xmlbuilder2 npm package to create a new file using nodejs.
xmlbuilder2 is a wrapper around DOM nodes which adds chainable functions to make it easier to create and work with XML documents.
How To Create A New XML File
Let’s create an XML file with nodes and attributes using xmlbuilder2.We’ll cover following functionality into this tutorial:
- Install & import package
- Created a root element
- Generate an XML file
- write and save in a XML file
The target XML file
Create an XML file that has the following content. We’ll create a main.js file and stored into the c:/workspace/create_xml/ folder.
post-request jsc://post-request.js
How To Install xmlbuilder2
You can install the npm packages by running the following command:
npm install xmlbuilder2 npm install fs
if you want to save into package.json
npm install xmlbuilder2 --save npm install fs --save
How To Install xmlbuilder2
At the top of the main.js file, and added below code into this file to import packages:
const < create >= require('xmlbuilder2'); const fs = require('fs');
Generate Xml File
We’ll generate xml file using following script:
let req_name = post-request; const root = create(< version: '1.0', encoding: "UTF-8", standalone: "yes" >) .ele('Javascript', < async: 'false', continueOnError: "false", enabled: "true", timeLimit: "200", name:req_name>) .ele('DisplayName').txt(req_name).up() .ele('Properties').up() .ele('ResourceURL').txt('jsc://'+req_name+'.js').up() .up(); const xml = root.end(< prettyPrint: true >); console.log(xml);
Write and Save XML File
Let’s write a file using fs module writeFileSync method and saved into the current directory.
let full_file_name = "./" + req_name + ".xml"; fs.writeFileSync(full_file_name, xml, function(err) < if (err) throw err; >);
The full Source:
The following is the full source code to create an XML file and save it into the current directory path.
const < create >= require('xmlbuilder2'); const fs = require('fs'); let req_name = 'post-request'; const root = create(< version: '1.0', encoding: "UTF-8", standalone: "yes" >) .ele('Javascript', < async: 'false', continueOnError: "false", enabled: "true", timeLimit: "200", name:req_name>) .ele('DisplayName').txt(req_name).up() .ele('Properties').up() .ele('ResourceURL').txt('jsc://'+req_name+'.js').up() .up(); const xml = root.end(< prettyPrint: true >); console.log(xml); let full_file_name = "./" + req_name + ".xml"; fs.writeFileSync(full_file_name, xml, function(err) < if (err) throw err; >);
Output:
post-request jsc://post-request.js
The create() function generates and returns a blank XML document node, while the ele function generates and returns an element node, and the up function returns its parent element node. You can think of up as the element node’s ending tag. The doc function returns the XML document’s document node. The end function finally converts the XML document to its string representation.
how to save xml files using Javascript?
I tried to use method save() to do 2). After my failure, I checked ms site and they said save() is not supported.
could some one enlighten me how to do the save?
W3Schools Internal Note
To:
From:
Message:
seems this is related to security issue. I appologize to those experienced programmers for my putting this question in a rush because it seems a newbie question.
Answers
Your problem is: javaScript does not have an input/output ( I/O ) API as it is a client-side scripting language and consequently has no access to the file system via the server. You would need to use a server-side scripting language to save data to a server. There may be hacks to solve your problem client-side, but they are probably either unsave or otherwise buggy. (btw: what api is the save method member of? Did you make that up?)
What you can do is save data temporarily to any DOM element (e.g. window, or a javaScript) object. There is however no way to make these changes permanent.
In your case, looking in to PHP scripting might be the best way to go.
The following will work in all major browsers, including IE 6:
var parseXml; if (typeof window.DOMParser != "undefined") < parseXml = function(xmlStr) < return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml"); >; > else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) < parseXml = function(xmlStr) < var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlStr); return xmlDoc; >; > else
var xml = parseXml("Stuff "); alert(xml.documentElement.nodeName);
var parseXml; if (typeof window.DOMParser != "undefined") < parseXml = function(xmlStr) < return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml"); >; > else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) < parseXml = function(xmlStr) < var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlStr); return xmlDoc; >; > else < throw new Error("No XML parser found"); >var xml = parseXml("Stuff "); document.body.innerHTML = "Root element: " + xml.documentElement.nodeName;
Readium Foundation just released Readium Web Components: see http://readium.org/news/announcing-readiumjs-a-javascript-library-for-browser-based-epub-3-reading (code: https://github.com/readium/Readium-Web-Components )
Alternatively, you might want to have a look at FuturePress: http://www.futurepress.org/ (code: https://github.com/fchasen/epub.js/ )
Finally, TEA also has something you might find interesting: https://github.com/TEA-ebook/teabook-open-reader
You want tagName , which is the name of the element. (Sorry about that, for Element s, tagName and nodeName are the same.)
The problem is that the first child of your myParent element isn’t the myChild element, it’s a text node (containing whitespace). Your structure looks like this:
- Element «myParent»
- Text node with a carriage return and some spaces or tabs
- Element «myChild»
- Text node with «content»
- Text node with a carriage return and some spaces or tabs
- Element «myChild»
- Text node with «content»
You need to navigate down to the actual myChild element, which you can do with getElementsByTagName again, or just by scanning:
var x=xmlDoc.getElementsByTagName("myParent"); var c = x[1].firstChild; while (c && c.nodeType != 1) < // 1 = ELEMENT_NODE c = c.nextSibling; >alert(c.nodeName); // "myChild"
Note that Element s don’t have a meaningful nodeValue property; instead, you collect their child text nodes. (More in the DOM specs: DOM2, DOM3.)
Also note that when indexing into a NodeList , the indexes start at 0 . You seem to have started with 1 ; ignore this comment if you were skipping the first one for a reason.
Off-topic: It’s always best to understand the underlying mechanics of what you’re working with, and I do recommend playing around with the straight DOM and referring to the DOM specs listed above. But for interacting with these trees, a good library can be really useful and save you a lot of time. jQuery works well with XML data. I haven’t used any of the others like Prototype, YUI, Closure, or any of several others with XML, so can’t speak to that, but I expect at least some of them support it.
Javascript save xml file
Asked by:
Question
User262732770 posted
hi all.. i want a code, which creates, then put content on xml file and then save that file on the local disk using javascript. this is all happening on a html file, so no server side coding will do the work. plz help guys. thnx in advance..All replies
User71929859 posted
Hi, Sorry to disappoint you. But I don’t think this is possible due to security reasons. Just imagine if there is a way to do this. Can you think of how much of a vulnerability the client machine is getting? However, you can achieve this using ActiveX. But remember ActiveX will only work in IE. Following CodeProject link will show you how to achive this using ActiveX. http://www.codeproject.com/KB/scripting/JavaScript__File_Handling.aspxUser527778624 posted
HI,instead of harddisk storage,
would u be interested in DOM storage(localStorage)?
then check these:create xml string via JS, parse it, save it!
Dev centers
Learning resources
Community
Support
Programs
© 2023 Microsoft