Sunday, 30 April 2017

Replace element with text using xmldom parser

I want to replace all ocurrances of a specific xml element:

<div><specificElement id="2">text</specificElement></div>

with some text based on a map, so for example having the following object:

{
  2: "replaced with"
}

I would get:

<div>replaced with</div>

How can I do this using the xmldom npm library? I've been trying the following:

const map = {2: "replaced with"};
const html = "<div><specificElement id="2">text</specificElement></div>";
const parser = new dom.DOMParser().parseFromString(html, "text/xml");
const tags = parser.getElementsByTagName("specificElement");
for (let i = 0; i < tags.length; i++) {
  const id = tags[i].getAttribute("id");
  const toReplace = map[id];
  tags[i].parentNode.replaceChild(tags[i], toReplace); // doesnt work
}
console.log(parser.toString());

But it does not change anything.



via user99999

No comments:

Post a Comment