xm-el
Simple XML creation using d3.js-inspired syntax.
Install
npm install xm-el
Examples
examples will reference the library as variable 'xml':
var xml = ;
Create Elements:
Create basic elements with xml.element(<tagname>)
var kerouac = xml;
Add a text node with .text()
kerouactext'Jack Kerouac';
Add attributes with .attr(<name>, <value>)
kerouac;
Get the markup as a string using .stringify()
kerouac;// '<author literary-movement="Beat">Jack Kerouac</author>'
Create self-closing elements with xml.element(<tagname>, true)
// create a self-closing element, set 2nd argument to 'true'var pagebreak = xml;pagebreak;// '<br />'
Multiple attributes can be assigned in a single call by passing a plain object to Element.attr()
var svg = xml ;
Chaining:
Creating an element or setting an attribute returns the element, which allows you to chain methods together:
xml text'Steve Reich' ;// '<composer last-name="Reich" genre="minimalism">Steve Reich</composer>'
Child Elements:
Create child elements using .append(<tagname>)
// some familiar namesvar members = 'John Lennon': 'guitar' 'Paul McCartney': 'bass' 'George Harrison': 'guitar' 'Ringo Starr': 'drums'; // lets say they're in a bandvar beatles = xml ; for var name in members // add each member using append() beatles textname; // gotta have a managerbeatles text'Brian Epstein';
Output to file:
Create an xml declaration with xml.declaration(<options>)
.
If no options are given, the default output is <?xml version="1.0"?>
the options argument is a plain object with 3 optional properties: version
, encoding
and standalone
.
// lets create a standalone file out of the beatles examplevar declaration = xml; // giving an argument to stringify() tidies output with the specified indentvar output = declaration + beatles;// write to file
beatles.xml
John Lennon Paul McCartney> George Harrison Ringo Starr Brian Epstein
Create a doctype with xml.doctype(<name>)
// create svg1.1 doctypevar doctype = xmldoctype'svg';var declaration = xml; // now lets write a simple svg filevar svg = xml ; var g = svg ; // create 10 random circles var circles = 10;while circles > 0 g ; circles--; // output a filevar output = declaration + doctype + svg;;
circles.svg