A very small and probably the fastest xml parser in pure javascript.
This lib is easy to use: txml.parse(xml);
.
- this code is about 255 lines, can be easily extended.
- this code is 1.6kb minified + gzipped.
- this code is 5 - 10 times faster than sax/xml2js and still 2-3 times faster than fast-xml-parser
- this code can running in a worker.
- this code is parsing at average the same speed as native DOMParser + potential to be faster.
- this code is easy to read and good for study.
- this code creates a domObject with minimal footprint, that is easy to traverse.
- this code has proven in different projects, like RSS reader, openStreetMap, websites.
- this code can even parse handwritten XML that contains various errors.
- this code is working in client and server.
- this code is 100% covered by unit tests.
- this.code is extreme small, perfect for browser, node, cloud function, edge.
so, there are good reasons to give tXml.js a try.
- tags
- childTags
- text-nodes
- white-spaces
- attributes with single and double quotes
- attributes without value
- xmlComments (ignored or keep)
- CDATA
- embedded CSS and Javascript
- HTML singleTag elements br, img, link, meta, hr (configurable)
- doctype definitions
- xml namespaces
- sync API for a sync process
- getElementsById/Class direct on the xmlString
- simplify, similar to PHP's SimpleXML
- simplifyLostLess
- filter, similar to underscore, as a alternative to CSS selectors
- monomorphism for fast processing and fewer if statements (a node always has tagName:'', attributes:{} and children:[])
- streamSupport ! ! !
- process stream with
for await
loop
Try without installing online: https://tnickel.de/2017/04/02/txml-online
- improved support for CDATA
- option to keep comments
- comment support for transformStream (comments inside elements are working, but not top level)
- allow options for transformStream
- export parser function only as
txml
, it will be the cleanest in all environments and let you usetxml.parse(xml)
where xml is the string. - remove
.parseStream
in favor oftransformStream
- more stable auto generated typescript definitions.
In browser you load it how ever you want. For example as tag: <script src="dist/txml.min.js"></script>.
In node and browserify, run "npm install txml" in your project
and then in your script you require it by const txml = require('txml');
or in typescript import * as txml from 'txml';
.
For specially small builds using modern module bundlers like rollup or webpack you can import txml/txml
or txml/dist/txml
. This will not add the transformStream into the bundle and with that exclude the Node.js files.
- xmlString is the XML to parse.
- options is optional
- searchId an ID of some object. that can be queried. Using this is incredible fast.
- filter a method, to filter for interesting nodes, use it like Array.filter.
- simplify to simplify the object, to an easier access.
- pos where to start parsing.
- keepComments if you want to keep comments in your data (kept as string including
<!-- -->
) (default false) - keepWhitespace keep whitespace like spaces, tabs and line breaks as string content (default false)
- noChildNodes array of nodes, that have no children and don't need to be closed. Default is working good for html. For example when parsing rss, the link tag is used to really provide an URL that the user can open. In html however a link text is used to bind css or other resource into the document. In HTML it does not need to get closed. so by default the noChildNodes contains the tagName 'link'. Same as 'img', 'br', 'input', 'meta', 'link'. That means: when parsing rss, it makes to set
noChildNodes
to [], an empty array.
txml.parse(`<user is='great'>
<name>Tobias</name>
<familyName>Nickel</familyName>
<profession>Software Developer</profession>
<location>Shanghai / China</location>
</user>`);
// will return an object like:
[{
"tagName": "user",
"attributes": {
"is": "great"
},
"children": [{
"tagName": "name",
"attributes": {},
"children": [ "Tobias" ]
}, {
"tagName": "familyName",
"attributes": {},
"children": [ "Nickel" ]
}, {
"tagName": "profession",
"attributes": {},
"children": [ "Software Developer" ]
}, {
"tagName": "location",
"attributes": {},
"children": [ "Shanghai / China" ]
}
]
}];
Same purpose of simplify, to make the data easier accessible. It is modeled after PHP
s simplexml. You can quickly access properties. However, some attributes might be lost. Also some string values can be lost. For details see Issue 19.
This method is used with the simplify
parsing option.
- tXml_DOM_Object the object to simplify.
txml.simplify(txml.parse(`<user is='great'>
<name>Tobias</name>
<familyName>Nickel</familyName>
<profession>Software Developer</profession>
<location>Shanghai / China</location>
</user>`));
// will return an object like:
{
"user": {
"name": "Tobias",
"familyName": "Nickel",
"profession": "Software Developer",
"location": "Shanghai / China",
"_attributes": {
"is": "great"
}
}
}
This version is not the same as in PHP simple_xml. But therefor, you do not lose any information. If there are attributes, you get an _attribute property, even if there is only one of a kind, it will be an array with one item, for consistent code.
This method is used with the filter parameter, it is used like Array.filter. But it will traverse the entire deep tree.
- tXml_DOM_Object the object to filter.
- f a function that returns true if you want this elements in the result set.
const dom = txml.parse(`
<html>
<head>
<style>
p { color: "red" }
</style>
</head>
<body>
<p>hello</p>
</body>
</html>`);
const styleElement = data.filter(dom, node=>node.tagName.toLowerCase() === 'style')[0];
To find an element by ID. If you are only interested for the information on, a specific node, this is easy and fast, because not the entire xml text need to get parsed, but only the small section you are interested in.
- xml the xml string to search in.
- id the id of the element to find returns return one node
Find the elements with the given class, without parsing the entire xml into a tDOM. So it is very fast and convenient. returns a list of elements.
- xml the xml string to search in.
- className the className of the element to find
- offset optional you to set short before the first item. usually files begin with something like "" so the offset need to be before the first item starts so that between that item and the offset is no "<" character. alternatively, pass a string, containing this preamble.
- options optional, similar to the parse methods options. return transformStream.
const xmlStream = fs.createReadStream('your.xml')
.pipe(txml.transformStream());
for await(let element of xmlStream) {
// your logic here ...
}
The transform stream is great, because when your logic within the processing loop is slow, the file read stream will also run slower, and not fill up the RAM memory. For a more detailed explanation read here
- version 5.1.0
- export ./* in package.json to allow older bundlers to import sub path directly.
import { parse } from 'txml/dist/txml.mjs';
- export ./* in package.json to allow older bundlers to import sub path directly.
- version 5.0.1
- fix simplify empty objects (issue #24)
- version 5.0.0
- improved handling of whitespace (issue #21)
- automated build with rollup (PR #23)
- version 4.0.1
- fixed children type definition not to include number (issue #20)
- add
hr
to self closing tags - new parser option
keepWhitespace
(issue #21)
Tobias Nickel German software developer in Shanghai.