Replace xml tag with nodejs

2

Hello, I would like some help to remedy a problem I am facing. I need to rename the tags of an xml file by nodejs. I thought about making use of regex, using fs to read the file, but I was kind of lost.

<RESULTS>
<ROW>
    <COLUMN NAME="DATA_CRIACAO"><![CDATA[24/08/18]]></COLUMN>
    <COLUMN NAME="PLACA"><![CDATA[ABC456]]></COLUMN>
    <COLUMN NAME="CHASSI"><![CDATA[XXXXXXXXXXXXXXX]]></COLUMN>
</ROW>
<ROW>
    <COLUMN NAME="DATA_CRIACAO"><![CDATA[23/08/18]]></COLUMN>
    <COLUMN NAME="PLACA"><![CDATA[ABC123]]></COLUMN>
    <COLUMN NAME="CHASSI"><![CDATA[YYYYYYYYYYYYYY]]></COLUMN>
</ROW>

Inside ROW we have ....., I need to rename each line of this to the content that is within NAME.

For example, rename from:

<COLUMN NAME="DATA_CRIACAO"><![CDATA[24/08/18]]></COLUMN>

To:

<DATA_CRIACAO><![CDATA[24/08/18]]></DATA_CRIACAO>

Thank you for your attention, thank you!

    
asked by anonymous 04.10.2018 / 08:15

1 answer

1

You can use the following regular expression within a replace to have the result you want:

/<COLUMN NAME="(.+)">(.+)<\/COLUMN>/gm

The complete code will be as follows:

const REGEX = /<COLUMN NAME="(.+)">(.+)<\/COLUMN>/gm;
let xml = '<ROW>
    <COLUMN NAME="DATA_CRIACAO"><![CDATA[24/08/18]]></COLUMN>
    <COLUMN NAME="PLACA"><![CDATA[ABC456]]></COLUMN>
    <COLUMN NAME="CHASSI"><![CDATA[XXXXXXXXXXXXXXX]]></COLUMN>
</ROW>
<ROW>
    <COLUMN NAME="DATA_CRIACAO"><![CDATA[23/08/18]]></COLUMN>
    <COLUMN NAME="PLACA"><![CDATA[ABC123]]></COLUMN>
    <COLUMN NAME="CHASSI"><![CDATA[YYYYYYYYYYYYYY]]></COLUMN>
</ROW>';

xml = xml.replace(REGEX, '<$1>$2</$1>');

console.log(xml);

The above expression performs the following steps:

  • <COLUMN NAME=" combines the literal set <COLUMN NAME=" (case sensitive);
  • Capture group (.+) :
    • .+ matches any character (except line terminations);
    • The quantifier + Combines between one and n times, as many times as possible;
  • "> matches the literal characters "> (case sensitive);
  • Capture group (.+) :
    • .+ matches any character (except line terminations);
    • The quantifier + Combines between one and n times, as many times as possible;
  • < combines the literal character < (case sensitive);
  • \/ combines the literal character / (case sensitive);
  • COLUMN> matches the literal characters COLUMN> (case sensitive).
05.10.2018 / 06:17