Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I do a command like array.shift() to an XML string?

I have an XML like this stored in a String variable in JavaScript :

<metadata>
<a>...</a>
<b>...</b>
<c>...</c>
</metadata>

<data>
<a>...</a>
<b>...</b>
<c>...</c>
</data>

Since a valid XML can only have single root tag, mine cannot be called valid as it has two root tags: metadata & data. I would like to completely remove the metadata tag, as I don’t have any use of it either.

I read about array.Shift() command, which removes the first element of an array. But since I have an XML, how do I do the same? Again, would just like to remove the <metadata> tag, so the result XML looks like this (given below).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<data>
<a>...</a>
<b>...</b>
<c>...</c>
</data>

>Solution :

Use a DOMParser

const xmlString = `
<metadata>
  <a>...</a>
  <b>...</b>
  <c>...</c>
</metadata>
<data>
  <a>...</a>
  <b>...</b>
  <c>...</c>
</data>`;

const parser = new DOMParser();
const doc1 = parser.parseFromString(`<root>${xmlString}</root>`, "application/xml");
doc1.querySelector('metadata').remove()
console.log(doc1.documentElement.innerHTML)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading