Replace xml tag with nodejs

Asked

Viewed 139 times

2

Hello, I would like a help to remedy a problem I am facing. I need to rename the tags of an xml file by nodejs. I thought about using regex, using Fs to read the file, but I got a little 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>

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

For example, renaming from:

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

for:

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

Thank you for your attention, thank you!

  • Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).

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);
  • Captures the group (.+):
    • .+ combines any character (except line endings);
    • The quantifier + Combines between a and n times, as many times as possible;
  • "> combines the literal characters "> (case sensitive);
  • Captures the group (.+):
    • .+ combines any character (except line endings);
    • The quantifier + Combines between a and n times, as many times as possible;
  • < combines the literal character < (case sensitive);
  • \/ combines the literal character / (case sensitive);
  • COLUMN> combines the literal characters COLUMN> (case sensitive).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.