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 = require('elementtree');var XML = et.XML;var ElementTree = et.ElementTree;var element = et.Element;var subElement = et.SubElement;var date, root, tenantId, serviceName, eventType, usageId, dataCenter, region,checks, resourceId, category, startTime, resourceName, etree, xml;date = new Date();root = element('entry');root.set('xmlns', 'http://www.w3.org/2005/Atom');tenantId = subElement(root, 'TenantId');tenantId.text = '12345'
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:
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 = require('fs');var et = require('elementtree');var XML = et.XML;var ElementTree = et.ElementTree;var element = et.Element;var subElement = et.SubElement;var data, etree;data = fs.readFileSync('document.xml').toString();etree = et.parse(data);console.log(etree.findall('./entry/TenantId').length); // 2console.log
Build status
License
node-elementtree is distributed under the Apache license.