jsxml is an XML library for javascript (and node)
npm install node-jsxmlAfter add this library to your project, there will be a global object named jsxml.
in HTML file, import using <script> elements.
<scriptsrc="jsxml.js"></script>in Node, import using require function.
constjsxml=require("node-jsxml");support AMD, CMD. Big thanks to TimSchlechter.
seajs.config({alias: {jsxml: '../src/jsxml.js'}});seajs.use('jsxml',function(jsxml){console.log(jsxml);});varNamespace=jsxml.Namespace,QName=jsxml.QName,XML=jsxml.XML,XMLList=jsxml.XMLList;Here you go:
varxml=newXML("<spring>"+"<list id='data'>"+"<element value='jsxml'/>"+"<element value='is'/>"+"<element value='an'/>"+"<element value='xml'/>"+"<element value='parser'/>"+"</list>"+"</spring>");find special childs
varchild=xml.child('list');find all children by *
varchildren=xml.child('*');print the xml string
console.log(xml.toXMLString());modify namespace
xml.addNamespace(newNamespace("ns","http://colorhook.com"));xml.children().addNamespace(newNamespace("prefix","uri"));console.log(xml.toXMLString());find descendants nodes
vardescendants=xml.descendants('element');get all children
varchildren=xml.children();//orvarchildren=xml.child('*');get text node
vartext=xml.text();get element node
varelements=xml.elements();get comment node
varcomments=xml.comments();get attribute
varattribute=xml.attribute("id");get all attributes
varattributes=xml.attributes();All methods above return an XML object or XMLList object, if you want to get the String type content, you should:
varxml=newXML(xmlContent);varattrValue=xml.attribute('attrName').toString();//orvarattrValue=xml.attribute('attrName').getValue();varchildA=xml.child('a').toString();//orvarchildA=xml.child('a').getValue();If you want to modify the value, you should call method setValue:
varxml=newXML("your xml string");varattr=xml.attribute('attrName');attr.setValue("newValue");varchildA=xml.child('a');childA.setValue("newValue");You can regenerate the XML Content
varstr=xml.toXMLString();While dealing with a list of childs in XML tree, you should use XMLList API:
varlist=xml.child("item");list.each(function(item,index){//item is an XML});You can also add, retrieve or remove namespaces:
varxml=newXML("your xml string");varns=xml.namespace("prefix");varnsNew=newNamespace("prefix",'uri');xml.addNamespace(nsNew);xml.removeNamespace(nsNew);Please feel free report bugs or feature requests. You can send me private message on [github], or send me an email to: [colorhook@gmail.com]
jsxml is free to use under MIT license.