Open maku opened 4 years ago
Here's a simple demo I wrote. You can take it as a reference :)
tagNameProcessor
is executed when entering a node while validator
is executed when leaving a node.
const xmlStr = `
<xml>
xml node text
<node1>
<!-- node1 node comment -->
node1 node text
<node2>
<!-- node2 node comment -->
node2 node text
</node2>
</node1>
<node3>
node3 node text
<!-- node3 node comment -->
</node3>
<!-- xml node comment -->
</xml>
`;
let currNode = "";
const tagNameProcessor = function (name) {
currNode = name;
return name;
};
const validator = function (xpath, node, obj) {
currNode = xpath.substring(0, xpath.lastIndexOf("/"));
currNode = currNode.substr(currNode.lastIndexOf("/") + 1);
return obj;
};
const parser = xml2js.Parser({ tagNameProcessors: [tagNameProcessor], validator: validator });
parser.saxParser.oncomment = function (str) {
console.log("node:", currNode, ",comment:", str);
};
parser.parseString(xmlStr, function (err, result) {
//do something
});
output:
node: node1 ,comment: node1 node comment
node: node2 ,comment: node2 node comment
node: node3 ,comment: node3 node comment
node: xml ,comment: xml node comment
How does one parse, process, manipulate object tree, and the build the XML output, but not lose comments? AFAICT this doesn't seem possible?
I have to manipulate an existing XML-File which contains comments.
How can I do this without loosing the comments in the file?