node-elementtree
node-elementtree is a Node.js XML parser and serializer based upon the Python ElementTree v1.3 module.
Installation
$ npm install elementtree
Using the library
For the usage refer to the Python ElementTree library documentation - http://effbot.org/zone/element-index.htm#usage.
Supported XPath expressions in find
, findall
and findtext
methods are listed on http://effbot.org/zone/element-xpath.htm.
Example 1 – Creating An XML Document
This example shows how to build a valid XML document that can be published to Atom Hopper. Atom Hopper is used internally as a bridge from products all the way to collecting revenue, called “Usage.” MaaS and other products send similar events to it every time user performs an action on a resource (e.g. creates,updates or deletes). Below is an example of leveraging the API to create a new XML document.
var et = ;var XML = etXML;var ElementTree = etElementTree;var element = etElement;var subElement = etSubElement; var date root tenantId serviceName eventType usageId dataCenter regionchecks resourceId category startTime resourceName etree xml; date = ; root = ;root; tenantId = ;tenantIdtext = '12345'; serviceName = ;serviceNametext = 'MaaS'; resourceId = ;resourceIdtext = 'enAAAA'; usageId = ;usageIdtext = '550e8400-e29b-41d4-a716-446655440000'; eventType = ;eventTypetext = 'create'; category = ;category; dataCenter = ;dataCentertext = 'global'; region = ;regiontext = 'global'; startTime = ;startTimetext = date; resourceName = ;resourceNametext = 'entity'; etree = root;xml = etree;console;
As you can see, both et.Element and et.SubElement are factory methods which return a new instance of Element and SubElement class, respectively. When you create a new element (tag) you can use set method to set an attribute. To set the tag value, assign a value to the .text attribute.
This example would output a document that looks like this:
12345 MaaS enAAAA 550e8400-e29b-41d4-a716-446655440000 create global global Sun Apr 29 2012 16:37:32 GMT-0700 (PDT) entity
Example 2 – Parsing An XML Document
This example shows how to parse an XML document and use simple XPath selectors. For demonstration purposes, we will use the XML document located at https://gist.github.com/2554343.
Behind the scenes, node-elementtree uses Isaac’s sax library for parsing XML, but the library has a concept of “parsers,” which means it’s pretty simple to add support for a different parser.
var fs = ; var et = ; var XML = etXML;var ElementTree = etElementTree;var element = etElement;var subElement = etSubElement; var data etree; data = fs;etree = et; console; // 2console; // MaaSconsole; // monitoring.entity.createconsole; // 1
Build status
License
node-elementtree is distributed under the Apache license.