![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
xml-reader
Advanced tools
The xml-reader npm package is a simple and lightweight XML parser that allows you to read and process XML data in a streaming manner. It is particularly useful for handling large XML files as it processes the data incrementally, reducing memory usage.
Streaming XML Parsing
This feature allows you to parse XML data in a streaming fashion. The code sample demonstrates how to set up an XML reader and listen for specific tags, extracting attributes and values as they are encountered.
const xmlReader = require('xml-reader');
const xmlQuery = require('xml-query');
const xml = '<root><child name="foo">bar</child></root>';
const reader = xmlReader.create();
reader.on('tag:child', function (data) {
console.log(data.attributes.name); // Outputs: foo
console.log(data.children[0].value); // Outputs: bar
});
reader.parse(xml);
xml2js is a popular XML parser that converts XML data into JavaScript objects. Unlike xml-reader, which processes XML in a streaming manner, xml2js reads the entire XML document into memory before parsing it, which can be less efficient for very large XML files.
sax is a streaming XML parser for JavaScript that is similar to xml-reader in that it processes XML data incrementally. However, sax is more low-level and provides a more detailed event-driven API, which can offer more control over the parsing process compared to xml-reader.
fast-xml-parser is a high-performance XML parser that can parse XML to JSON and vice versa. It is designed for speed and efficiency, making it a good alternative to xml-reader for applications where performance is critical. Unlike xml-reader, it provides both synchronous and asynchronous parsing options.
Reads XML documents and emits JavaScript objects with a simple, easy to use structure.
npm install --save xml-reader
Objects emitted by the reader are trees where each node has the following structure:
interface XmlNode {
name: string; // element name (empty for text nodes)
type: string; // node type (element or text), see NodeType constants
value: string; // value of a text node
parent: XmlNode; // reference to parent node (null with parentNodes option disabled or root node)
attributes: {[name: string]: string}; // map of attributes name => value
children: XmlNode[]; // array of children nodes
}
Added the tagPrefix
option with a default value of 'tag:'
. This way we avoid possible name collisions with the done
event.
To keep the old behavior, set it to an empty string.
Check the xml-query
package! It is very useful to read values from the structures returned by xml-reader
.
Basic example. Read and parse a XML document.
const XmlReader = require('xml-reader');
const reader = XmlReader.create();
const xml =
`<?xml version="1.0" encoding="UTF-8"?>
<message>
<to>Alice</to>
<from>Bob</from>
<heading color="blue">Hello</heading>
<body color="red">This is a demo!</body>
</message>`;
reader.on('done', data => console.log(data));
reader.parse(xml);
/*
Console output:
{ name: 'message',
type: 'element',
children: [
{ name: 'to',
type: 'element',
children: [{ type: 'text', value: 'Alice' }]},
{ name: 'from',
type: 'element',
children: [{ type: 'text', value: 'Bob' }]},
{ name: 'heading',
type: 'element',
attributes: { color: 'blue' },
children: [{ type: 'text', value: 'Hello' }]},
{ name: 'body',
type: 'element',
attributes: { color: 'red' },
children: [{ type: 'text', value: 'This is a demo!' }]}]}
Note: empty values and references to parent nodes removed for brevity!
*/
This mode is only valid for reading complete documents (root node must be closed).
const XmlReader = require('xml-reader');
const xml = '<doc>Hello!</doc>';
const result = XmlReader.parseSync(xml/*, options*/);
In stream mode, nodes are removed from root as they are emitted. This way memory usage does not increases.
const XmlReader = require('xml-reader');
const reader = XmlReader.create({stream: true});
const xml =
`<root>
<item v=1/>
<item v=2/>
<item v=3/>
</root>`;
reader.on('tag:item', (data) => console.log(data));
// {name: 'item', type: 'element', value: '', attributes: {v: '1'}, children: []}
// {name: 'item', type: 'element', value: '', attributes: {v: '2'}, children: []}
// {name: 'item', type: 'element', value: '', attributes: {v: '3'}, children: []}
reader.on('done', (data) => console.log(data.children.length));
// 0
reader.parse(xml);
You can also listen to all tags:
reader.on('tag', (name, data) => console.log(`received a ${name} tag:`, data));
In this example we are calling multiple times to the parser. This is useful if your XML document is a stream that comes from a TCP socket or WebSocket (for example XMPP streams).
Simply feed the parser with the data as it arrives. As you can see, the result is exactly the same as the previous one.
const XmlReader = require('xml-reader');
const reader = XmlReader.create({stream: true});
const xml =
`<root>
<item v=1/>
<item v=2/>
<item v=3/>
</root>`;
reader.on('tag:item', (data) => console.log(data));
// {name: 'item', type: 'element', value: '', attributes: {v: '1'}, children: []}
// {name: 'item', type: 'element', value: '', attributes: {v: '2'}, children: []}
// {name: 'item', type: 'element', value: '', attributes: {v: '3'}, children: []}
reader.on('done', (data) => console.log(data.children.length));
// 0
// Note that we are calling the parse function providing just one char each time
xml.split('').forEach(char => reader.parse(char));
Use the reset()
method to reset the reader. This is useful if a stream gets interrupted and you want to start a new one or to use the same reader instance to parse multiple documents (just reset the reader between them).
Example:
const doc1 = '<document>...</document>';
const doc2 = '<document>...</document>';
reader.parse(doc1);
// when the document ends, the reader stops emitting events
reader.reset();
// now you can parse a new document
reader.parse(doc2);
Default options are:
{
stream: false,
parentNodes: true,
tagPrefix: 'tag:',
doneEvent: 'done',
emitTopLevelOnly: false,
}
If true
(default), each node of the AST has a parent
node which point to its parent. If false
the parent node is always null
.
Enable or disable stream mode. In stream mode nodes are removed from root after being emitted. Default false
.
Ignored in parseSync
;
Default value is 'done'
. This is the name of the event emitted when the root node is closed and the parse is done.
Ignored in parseSync
;
Default value is 'tag:'
. The event driven API emits an event each time a tag is read. Use this option to set a name prefix.
Ignored in parseSync
;
Default value is false
. When true, tag events are only emitted by top level nodes (direct children from root). This is useful for XMPP streams like XMPP where each top level child is a stanza.
For example, given the following XML stream:
<stream>
<message from="alice" to="bob">
<body>hello</body>
<date>2016-10-06</date>
</message>
<message from="alice" to="bob">
<body>bye</body>
<date>2016-10-07</date>
</message>
tags emitted with emitTopLevelOnly=false
body
date
message
body
date
message
tags emitted with emitTopLevelOnly=true
message
message
MIT
FAQs
XML Reader and Parser
The npm package xml-reader receives a total of 0 weekly downloads. As such, xml-reader popularity was classified as not popular.
We found that xml-reader demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.