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

Time:11-28

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).

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

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Since you talk about a string, just search for '<data>' and get the substring from that position to the end:

let str = `
    <metadata>
      <a>...</a>
      <b>...</b>
      <c>...</c>
    </metadata>
    
    <data>
      <a>...</a>
      <b>...</b>
      <c>...</c>
    </data>
    `

let data = str.substring(str.search('<data>'))

console.log(data)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or search for '</metadata>' plus two new line characters to find the start of :

let data = str.substring(str.search('</metadata>\n\n')   13)
  • Related