■XML解析
function parseXML(xml) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, "application/xml");
return xmlToJson(xmlDoc);
}
function xmlToJson(xml) {
const obj = {};
if (xml.nodeType === 1) { // element
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (let j = 0; j < xml.attributes.length; j++) {
const attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType === 3) { // text
obj = xml.nodeValue;
}
if (xml.hasChildNodes()) {
for(let i = 0; i < xml.childNodes.length; i++) {
const item = xml.childNodes.item(i);
const nodeName = item.nodeName;
if (typeof(obj[nodeName]) === "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) === "undefined") {
const old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
// サンプルXMLデータ
const xmlData = `
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>`;
const jsonData = parseXML(xmlData);
console.log(JSON.stringify(jsonData, null, 2));
■XML階層出力
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>JSON Viewer</title>
<style>
ul {
list-style-type: none;
}
.toggle {
cursor: pointer;
color: blue;
text-decoration: underline;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<div id="jsonViewer"></div>
<script>
document.addEventListener("DOMContentLoaded", function() {
const jsonData = {
"note": {
"to": "Tove",
"from": "Jani",
"heading": "Reminder",
"body": "Don't forget me this weekend!"
}
};
function createTreeView(json, container) {
const ul = document.createElement("ul");
for (const key in json) {
if (json.hasOwnProperty(key)) {
const li = document.createElement("li");
if (typeof json[key] === "object" && json[key] !== null) {
li.innerHTML = `<span class="toggle">[+]</span> ${key}`;
const subContainer = document.createElement("div");
subContainer.classList.add("hidden");
createTreeView(json[key], subContainer);
li.appendChild(subContainer);
} else {
li.textContent = `${key}: ${json[key]}`;
}
ul.appendChild(li);
}
}
container.appendChild(ul);
}
function addToggleFunctionality() {
document.querySelectorAll(".toggle").forEach(function(toggle) {
toggle.addEventListener("click", function() {
const subContainer = this.nextElementSibling;
if (subContainer.classList.contains("hidden")) {
subContainer.classList.remove("hidden");
this.textContent = "[-]";
} else {
subContainer.classList.add("hidden");
this.textContent = "[+]";
}
});
});
}
const container = document.getElementById("jsonViewer");
createTreeView(jsonData, container);
addToggleFunctionality();
});
</script>
</body>
</html>
0 件のコメント:
コメントを投稿