I have the following function, which takes a two xml strings as input and then compares them and creates a html output showing the differences marked in red.
function compareXml(xml1, xml2) {
xml1 = formatXml(xml1);
xml2 = formatXml(xml2);
let html = "<table>";
let lineNo = 0;
let xml1Nodes = xml1.split("\n");
let xml2Nodes = xml2.split("\n");
for (let i = 0; i < Math.max(xml1Nodes.length, xml2Nodes.length); i++) {
lineNo++;
let xml1Line = xml1Nodes[i];
let xml2Line = xml2Nodes[i];
let xml1Node = xml1Line.replace(/</g, "<").replace(/>/g, ">");
let xml2Node = xml2Line.replace(/</g, "<").replace(/>/g, ">");
if (xml1Line !== xml2Line) {
html += "<tr><td class='xml1' style='background-color:red'>" + "Zeile: " + lineNo + " " + xml1Node + "</td><td class='xml2' style='background-color:red'>" + "Zeile: " + lineNo + " " + xml2Node + "</td></tr>";
} else {
html += "<tr><td class='xml1'>" + "Zeile: " + lineNo + " " + xml1Node + "</td><td class='xml2'>" + "Zeile: " + lineNo + " " + xml2Node + "</td></tr>";
}
}
html += "</table>";
return html;
}
the following function is called to format the xml correcly (indentation) but the problem is that the indentation won't get removed, when the xml tag gets closed.
function formatXml(xml) {
let formatted = "";
let indent = "";
let nodes = xml.match(/(<[^\/][^>]*>|<\/[^>]+>|[^<]+)/g);
nodes.forEach(function(node) {
if (node.startsWith("<")) {
formatted += indent + node;
if (!node.endsWith("/>")) {
if (nodes.length > nodes.indexOf(node) + 1 && nodes[nodes.indexOf(node) + 1].startsWith("<")) {
formatted += "\n";
indent += " ";
}
}
} else if (node.startsWith("</")) {
indent = indent.substring(6);
formatted += indent + node + "\n";
} else {
formatted += node;
}
});
return formatted;
}
The return value of the compareXml Function then gets put into a IFrame where it should display the XML correctly formatted. I'm glad for any answers or inputs to point me in the right direction since JS is not my area :)
Thanks already!
I get the following output when printing it to the console:
<?xmlversion="1.0"encoding="utf-16"?>
<testxml>
<xml>
<title>TestXml </title>
</xml>
</testxml>
as you can see, the indentation won't get removed and only gets added further. I tried a lot of things by tweaking my code but I'm somehow not able to figure it out.
Via Active questions tagged javascript - Stack Overflow https://ift.tt/qpuJKsz
Comments
Post a Comment