solutaaliquid
Version:
common utils for javascript. Utils to get the global scope (browser, webworker & co.). Customizable string escaper. Utilitize for objects. Extension at base javascript api (usefull extention like String.hashcode()).
53 lines (42 loc) • 1.46 kB
JavaScript
const ATTRIBUTE_PRFIX = "@";
const TEXTCONTENT = "@";
const parse = (content) => {
const parser = new DOMParser();
return parser.parseFromString(content, "application/xml");
};
const xmlToJson = (node) => {
// Create the return object
if (node.nodeType == 3 || node.nodeType == 4) return node.textContent.trim();
const hasAttributes = node.attributes && node.attributes.length > 0;
const hasChildNodes = node.childElementCount > 0;
if (!hasAttributes && !hasChildNodes) return node.textContent.trim();
// process childs
const obj = {};
let textContent = "";
// element do attributes
if (hasAttributes) {
for (let attribute of node.attributes) obj[`${ATTRIBUTE_PRFIX}${attribute.nodeName}`] = attribute.nodeValue;
}
for (let item of node.childNodes) {
if (item.nodeType == 1) {
const nodeName = item.nodeName;
if (typeof obj[nodeName] === "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof obj[nodeName].push === "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
} else if (item.nodeType == 3 || item.nodeType == 4) textContent = textContent + item.textContent;
}
textContent = textContent.trim();
if (textContent.length > 0) obj[TEXTCONTENT] = textContent;
return obj;
};
export default (content) => {
if (typeof content === "string") content = parse(content);
return xmlToJson(content);
};