npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

xelement

v1.0.17

Published

A powerful xelement (Xml Element) class for JavaScript.

Downloads

1,787

Readme

Build Status

xelement

A powerful JavaScript xelement (Xml Element) class to parse xml for NodeJs and Browser (Typescript included).


xelement represents an xml element. You can use this class to create or parse xml string to xml element. It allows to add, edit and delete any element or its attributes within the element tree and serialize the entire element to string from. You can search through the element and can traverse the element tree up and downwards.

The basic building blocks of this module are XElement class and Parser

  • XElement class represents each element in the xml element tree.
  • Parse will create XElement tree from the xml string.
  • ParseJson will create XElement tree from JSON string or JSON object.

Installation for node

npm install xelement --save

Usage

	
	var xelement = require('xelement');	
	var xeleRoot = xelement.Parse("<root><ele1>some value</ele1></root>"); //Parsing from xml string
	//or	
	var xeleRoot = xelement.ParseJson({ name : "teja" , place : "Hyderabad"} ); //Parsing from JSON Object
	//or
	var xeleRoot = xelement.ParseJson('{ "name" : "teja", "place" : "Hyderabad" }'); //Parsing from JSON string	
	

XElement class The main class is XElement which represents the parsed xml, all elements in the XElement tree from root to leaf element are XElement.

Members

  • name: name of the element or node name “<root>”. For more information about namespaces please refer to sax.
  • attr: an object represents all attributes of the element. The default value is {}. Ex: - book.attr.id where <book id=”bk108”>
  • value: value of the element. Ex: - book.value returns “some value”where <book>some value</book>
  • elements: array of child elements. The default value is [].
  • parent: refers to the parent element. Ex: - author.parent.name will return “book” where <book><author>tj</author></book>

Features

Parse(data) Converts xml string to XElemnt

	var fs = require('fs');
	var xelement = require('xelement');
	var xmlString = fs.readFileSync('./sampledata.xml', 'utf8');
	xeleCatalog = xelement.Parse(xmlString); //parses the xmlString to XElement object representing complete xml element tree

ParseJson(data,elementName) Converts json string or object to XElement elementName: elementName

	var obj = {
		"name" : "teja",
		"location" : "hyderabad"
	}

	var xelement = require('xelement', "elementRootName");
		xeleCatalog = xelement.ParseJson(obj); //parses the Json string/object to XElement object representing complete xml element tree	

Example Xml

You can find sample xml at here

Methods


descendants(name, ignoreCase) Returns the array of all descendant element with specified name by default parameter is empty on unspecified and it will return all descendant elements, ignoreCase is the flag whether to ignore the case of the element name, by default set to false. On unsuccessful result it will return [].

	var descs = xeleCatalog.descendants('author', true);	//returns all elements with “author” name

descendantsAndSelf(name, ignoreCase) Returns the array of all descendant element with specified name and self by default parameter is empty on unspecified and it will return all descendant elements, ignoreCase is the flag whether to ignore the case of the element name, by default set to false. On unsuccessful result it will return [].

	var descs = xeleCatalog.descendantsAndSelf('author', true); //returns all elements with “author” name including self

descendantFirst(name, ignoreCase) Returns the first descendant element with specified name, name is not optional , ignoreCase is the flag whether to ignore the case of the element name, by default set to false. On unsuccessful result it will undefined.

	var descs = xeleCatalog.descendantsFirst('author', true); //returns the first element with “author” name

ancestor(name, ignoreCase) Returns the ancestor parent with specified name. ignoreCase is the flag whether to ignore the case of the element name, by default set to false. On unsuccessful result it will return undefined.

	var author = xele.descendantsFirst('author');
	var book = author.ancestor('book'); //returns the book element
	var catalog= author.ancestor('catalog');   //return the catalog element

firstElement() Returns the first child element, returns undefine if doesn’t exist.

	var author = xele.descendantsFirst(book);
	var author = author.firstElement(); //returns the author element

lastElement() Returns the last child element, return undefined if doesn’t exist.

	var author = xele.descendantsFirst(book);
	var description = author.lastElement(); //returns the description element

siblings(name) Returns the siblings of the element with specified name, if name unspecified it returns all siblings. Return [] if doesn’t exist.

	var author = xele.descendantsFirst('author');
	var sl[] = xele.siblings(); //returns all sibling elements

previousSibling() Returns the previous sibling of the element, it returns undefined if doesn’t exist.

	var fd = xeleCatalog.descendantFirst('title', true);
	var ps = fd.previousSibling();
	console.log(ps.name); //prints “author”
	console.log(fd.previousSibling().previousSibling()); //prints undefined

nextSibling() Returns the next sibling of the element, it returns undefined if doesn’t exist.

	var fd = xeleCatalog.descendantFirst('publish_date', true);
	var ps = fd.nextSibling();
	console.log(ps.name); //prints “description”
	console.log(fd.nextSibling().nextSibling()); //prints undefined

index() Returns the index of the element among its sibling. Index starts from 0. It returns undefined if the element is not a child other element.

	var fd = xeleCatalog.elements.where(function (o) { return o.attr.id == "bk104"; });
	console.log(fd[0].index()); //prints 3

setAttr(name, value) Sets the value to specified attribute of the element. If the attribute doesn’t exist, it will create.

	var fd = xeleCatalog.descendantFirst('book');
	fd.setAttr('NewAttr', '100');
	console.log(fd.attr.NewAttr); //prints “100”   

getAttr(name) Returns the value from specified attribute of the element. If the attribute doesn’t exist it will return empty.

	var fd = xeleCatalog.descendantFirst('book');
	fd.setAttr('NewAttr', '100');
	console.log(fd.getAttr('NewAttr')); //prints “100” 
	console.log(fd.getAttr('yyy')); //prints empty

removeAttr(name) Remove the specified attribute from the element.

	var fd = xeleCatalog.descendantFirst('book');
	fd.removeAttr('NewAttr', '100');
	console.log(fd.attr.NewAttr); //prints undefined
	console.log(fd.getAttr('NewAttr')); //prints empty

add(obj) Adds xelement as its child element. Single or array of xelement can be passed. Only valid xelement object will be added and others ignored.

	var dummy = {};
	xeleCatalog.add(dummy);//adding invalid object it will ignore     
	console.log(xeleCatalog.lastElement().attr.id); //prints “bk112” because the {} object didn’t add to xeleCatalog element.
	
	//adding single element
	var newBook = new xelement.XElement("book");
	newBook.attr.id = "bk113";
	xeleCatalog.add(newBook);
	console.log(xeleCatalog.lastElement().attr.id); //prints “bk113”
	
	//Adding range of elements
	var newElements = [];
	for (var i = 0; i < 5; i++) {
		newBook = new xelement.XElement("book");
		newBook.attr.id = "bk" + (113 + i).toString();
		newElements.push(newBook);
	}
	xeleCatalog.add(newElements);    
	console.log(xeleCatalog.lastElement().attr.id) //prints “bk117”    

createElement(name,value) Create a new element and adds to its child elements. If value parameter is unspecified it will consider as empty.

	var newEle = xeleCatalog.createElement("TestElement");
	newEle.value = "100";  
	console.log(xeleCatalog.lastElement().name); //prints “TestElement”
	
	//or
	var newEle = xeleCatalog.createElement("TestElement", "100");  
	console.log(newEle.value); //prints “100”

element(name, ignoreCase) Return the first element with specified name, name is not optional. It returns undefined if doesn’t exist.

	var fd = xeleCatalog.element('book1');
	console.log(fd); //prints undefined
	fd = xeleCatalog.element('book');
	console.log(fd.name); //prints “book”

getElements(name, ignoreCase) Return the all elements with specified name, if name unspecified it will return all child elements.

	var eles = xeleCatalog.getElements('book', true); //return all elements with “book” name

getElementValue(name, ignoreCase) Return the first element value with specified name, name is not optional.

	var vl = xeleCatalog.getElementValue("TestElement1", true);
	console.log(vl); //prints TestElement1 element value

setElementValue(name,value) Sets the specified child element value. If element doesn’t exist it will create new.

	xeleCatalog.setElementValue("TestElement", 1001); 
	console.log(xeleCatalog.getElementValue("TestElement")); //prints 1001

hasElements return true if the element has any child elements.

	if(xeleCatalog.hasElements)
	console.log('has elements'); 

hasAttr return true if the element has any attribues.

	if(xeleCatalog.hasAttr)
	console.log('has attribues'); 

remove() Remove the current element from its parent. The element will be no longer associated with element tree.

	var fd = xeleCatalog.descendantFirst('book');
	fd.remove(); //remove the book element from its parent

removeAll() Removes the all child elements. All child elements will be no longer associated with element tree.

	var fd = xeleCatalog.descendantFirst('book');
	fd.removeAll(); //remove all child element from book element

toXmlString() Converts the xelement into valid xml string. This function is available for each element in the tree thus xml string can be created from any element from the tree.

	var fd = xeleCatalog.descendantFirst('book');
	console.log(fd.toXmlString())
	//prints the following xml
	<book id="bk101">
		<author>Gambardella, Matthew</author>
		<title>XML Developer's Guide</title>
		<genre>Computer</genre>
		<price>44.95</price>
		<publish_date>2000-10-01</publish_date>
		<description>
			An in-depth look at creating applications with XML.
		</description>
	</book>

toJSON(options) Converts the xelement into JSON object. This function is available for each element in the tree thus JSON object can be created from any element from the tree.
options : { includeAttributes : true/false to specifiy to include attrubes in the JSON. default value is fale }

	var fd = xeleCatalog.descendantFirst('book');
	console.log(fd.toJSON())
	//prints the following JSON
	{
		"@id": "bk101",
		"author": "Gambardella, Matthew",
		"title" : "XML Developer's Guide",
		"genre" : "Computer",
		"price" : "44.95",
		"publish_date" : "2000-10-01",
		"description" : "An in-depth look at creating applications with XML."
	}

Array Extensions Array extension methods will facilitate search, select, foreach operations on collection of items

where(fn) Is an extension method to an array to enable to apply filter to its collection as array. The default value is [].

	var wr = xeleCatalog.descendants("book").where(function (o) { return o.attr.id == "bk109" });

select(fn) Is an extension method to an array to select any object or object value as array. The default value is [].

	var wr = xeleCatalog.descendants("author").select(function (o) { return o.value; });

selectMany(fn) Is an extension method to an array to select Many and returns a single array. The default value is [].

	var wr = xeleCatalog.descendants("book").selectMany(function (o) { return o.elements });

forEach(fn) Is an extension method to an array to execute operation on each item in the array.

	var wr = xeleCatalog.descendants("book");
	wr.forEach(function (o) {
		o.setAttr('newAttr', 'someValue');
		o.createElement('newElement', 'someValue');
   	});

Feedback and Comments


Please feel free to post your comments on Twitter and issues on github