rexml

rexml
is a Node.JS package for simple XML parsing with a regular expression. It's been tested to work for simple use cases (does work on nested tags).
yarn add rexml
Table Of Contents
API
The package is available by importing its default and named functions:
import rexml, { extractProps, extractTagsSpec, extractPropSpec } from 'rexml'
rexml(
tag: string,
string: string,
): {content, props}[]
Extract tags from the XML string. The tags are returned as an array with objects containing content
and props
properties. The content is the inner content of the tag, and props
is the attributes specified inside the tag.
import extractTags from 'rexml'
const xml = `
<html>
<div id="d1"
class="example"
contenteditable />
<div id="d2" class="example">Hello World</div>
</html>
`
const res = extractTags('div', xml)
console.log(JSON.stringify(res, null, 2))
[
{
"content": "",
"props": {
"id": "d1",
"class": "example",
"contenteditable": true
}
},
{
"content": "Hello World",
"props": {
"id": "d2",
"class": "example"
}
}
]
Extracts the properties from the attributes part of the tag and returns them as an object. It will parse values if not specified otherwise.
Source | Output |
---|
import { extractProps, extractPropsSpec } from 'rexml'
const s = `id="d2"
class="example"
value="123"
parsable="true"
ignore="false"
2-non-spec
required`
const res = extractProps(s)
console.log(JSON.stringify(res, null, 2))
const res2 = extractProps(s, false)
console.log(JSON.stringify(res2, null, 2))
const res3 = extractPropsSpec(s)
console.log(JSON.stringify(res3, null, 2))
|
{
"id": "d2",
"class": "example",
"value": 123,
"parsable": true,
"ignore": false,
"2-non-spec": true,
"required": true
}
{
"id": "d2",
"class": "example",
"value": "123",
"parsable": "true",
"ignore": "false",
"2-non-spec": true,
"required": true
}
{
"id": "d2",
"class": "example",
"value": 123,
"parsable": true,
"ignore": false,
"required": true
}
|
Same as the default method, but confirms to the XML specification in defining attributes.
import { extractTagsSpec } from 'rexml'
const xml = `
<html>
<div id="d1" class="example" contenteditable />
<div 5-non-spec>Attributes cannot start with a number.</div>
</html>`
const res = extractTagsSpec('div', xml)
console.log(JSON.stringify(res, null, 2))
[
{
"props": {
"id": "d1",
"class": "example",
"contenteditable": true
},
"content": ""
}
]
Copyright