Lightweight schema-based XML data extraction to plain objects (JSON)
npm install xmldom-js
xmldom-js
===
Lightweight schema-based XML data extraction to plain objects (JSON)
To read the data from the following XML
``xml
`
Data extraction schema:
`js
import { attribute, content, string, readXML, prefixNamespace } from "xmldom-js";
var rssSchema = {
rss: {
channel: {
title: content(string),
item: [{
title: content(string),
"media:content": { url: attribute() },
"media:comment": content(string)
}]
}
}
};
`
First xml is parsed using the browser DOMParser and then read into plain JS objects using the schema:
`js
var rssXml = new DOMParser().parseFromString(rssString, "text/xml");
var rssJSON = readXML(rssXml, rssSchema, prefixNamespace);
`
The resulting JSON:
`json``
{
"rss": {
"channel": {
"title": "MRSS Title",
"item": [
{
"title": "Item 1",
"media:content": {
"url": "http://example.com/1.mp4"
},
"media:comment": "Item 1 Comment"
},
{
"title": "Item 2",
"media:content": {
"url": "http://example.com/2.mp4"
},
"media:comment": "Item 2 Comment"
}
]
}
}
}