-2

I have the xml as text.

I need to extract the string "20" between the tags:

<ans:sequencialTransacao>2020</ans:sequencialTransacao>

I have tried the script below, but it doesn't work.

const matches = this.codeXML.matchAll(
        /<ans:sequencialTransacao> (.*?) <\/ans:sequencialTransacao>/gm
      );
console.log(Array.from(matches, (x) => x[1])); 

//XML

<ans:identificacaoTransacao>
     <ans:tipoTransacao>ENVIO_LOTE_GUIAS</ans:tipoTransacao>
     <ans:sequencialTransacao>20</ans:sequencialTransacao>
     <ans:dataRegistroTransacao>2020-07-13</ans:dataRegistroTransacao>
     <ans:horaRegistroTransacao>20:48:28</ans:horaRegistroTransacao>
</ans:identificacaoTransacao>
Nanoo
  • 836
  • 8
  • 16
Luiz Alves
  • 2,575
  • 4
  • 34
  • 75

1 Answers1

2

If you need a quick & dirty solution, try this:

var xml = `<ans:identificacaoTransacao>
      <ans:tipoTransacao>ENVIO_LOTE_GUIAS</ans:tipoTransacao>
      <ans:sequencialTransacao>20</ans:sequencialTransacao>
      <ans:dataRegistroTransacao>2020-07-13</ans:dataRegistroTransacao>
      <ans:horaRegistroTransacao>20:48:28</ans:horaRegistroTransacao>
 </ans:identificacaoTransacao>`

xml.split("<ans:sequencialTransacao>")[1].split("<")[0]; // Returns "20"

Otherwise, check out xml2json.


New solution (more clean):

function getXMLValue(tagName, xmlStr) {
    var tagValue = xmlStr.substring(
        xmlStr.lastIndexOf(tagName) + tagName.length,
        xmlStr.lastIndexOf(tagName.replace("<", "</"))
    );
    return tagValue;
}

Usage:

var xml = `<ans:identificacaoTransacao>
      <ans:tipoTransacao>ENVIO_LOTE_GUIAS</ans:tipoTransacao>
      <ans:sequencialTransacao>20</ans:sequencialTransacao>
      <ans:dataRegistroTransacao>2020-07-13</ans:dataRegistroTransacao>
      <ans:horaRegistroTransacao>20:48:28</ans:horaRegistroTransacao>
 </ans:identificacaoTransacao>`;

getXMLValue("<ans:sequencialTransacao>", xml); // Returns "20"
Nanoo
  • 836
  • 8
  • 16
  • No problem, I updated my answer with a new & more clean solution. Simply provide the name of the xml element, and the xml string - this returns the value of that element. – Nanoo Jul 24 '20 at 14:43
  • **Warning:** Never parse XML manually like this. Very unreliable. "More clean" is still a terrible approach. Use a real XML parser. Downvoted. – kjhughes Jul 24 '20 at 16:22
  • ...And I said it was "unreliable"? It does exactly what he needs - sure there are probably other ways of doing it, but there are no native functions for reading XML in JavaScript. Also, I did mention "xml2json" - which is a "real XML parser" library. – Nanoo Jul 24 '20 at 19:58
  • 1
    Didn't mean to set off any emotions - it's just XML, calm down. If you think you have a better solution, then perhaps leave an answer instead? It will be useful for anyone who comes across this **duplicate** topic. – Nanoo Jul 24 '20 at 20:22
  • Thank you. This solved my problem – Luiz Alves Jul 27 '20 at 12:29