You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.4 KiB
JavaScript

fetch("test.xml")
.then((res) => res.text())
.then((data) => {
parseDocument(data);
});
const parseDocument = function (data) {
const parser = new DOMParser();
const doc = parser.parseFromString(data, "application/xml");
const container = document.querySelector("#container");
const levels = document.querySelector("#controller");
container.innerHTML = "";
levels.innerHTML = "";
const errorNode = doc.querySelector("parsererror");
if (errorNode) {
let error = document.createElement("span");
error.style.color = "tomato";
error.innerHTML = "Error while parsing the XML file! Check if the document is well formed";
levels.appendChild(error);
} else {
controller(layers(doc));
display(doc);
}
};
const layers = function (xml) {
return new Set([...xml.querySelectorAll("*")].map((node) => node.tagName));
};
const controller = function (levels) {
const controller = document.querySelector("#controller");
for (const level of levels) {
let check = document.createElement("input");
check.type = "checkbox";
check.checked = true;
check.value = level;
let label = document.createElement("label");
label.for = level;
label.innerHTML = level;
controller.appendChild(check);
controller.appendChild(label);
check.addEventListener("change", (el) => {
console.log(check.checked);
setVisibility(check.checked, level);
});
}
};
const setVisibility = function (visibility, selector) {
let elements = document.getElementsByClassName(selector);
for (const el of elements) {
el.style.display = visibility ? "initial" : "none";
}
};
const display = function (doc) {
const container = document.querySelector("#container");
traverse(doc.documentElement, (el) => {
let block = document.createElement("span");
block.classList.add(el.parentNode.tagName);
block.innerHTML = el.textContent;
container.appendChild(block);
});
};
const traverse = function (el, callback) {
if (el.childNodes.length) {
for (const child of el.childNodes) {
traverse(child, callback);
}
} else {
if (typeof callback == "function") {
callback(el);
}
}
};
const fileSelector = document.getElementById("file-selector");
fileSelector.addEventListener("change", (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.addEventListener("load", (event) => {
parseDocument(event.target.result);
});
reader.readAsText(file);
});