noDe1
noDe1

Reputation: 331

Changing value of XML data using Node JS

I have a XML document that looks like this:

 <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>abcdefg</information>
</Data>

I would like to change the information data abcdefg to a different piece of string that comes from a different variable.

So it looks like this:

 <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>example</information>
</Data>

Is this possible to do directly in Node JS without changing this XML to a json, modifying it and then converting back to XML? I have tried this however it did not seem to work, creating weird arrays and '$' on the XML conversion.

Any suggestions on how I could do this?

Upvotes: 2

Views: 5942

Answers (2)

Angels
Angels

Reputation: 230

1)You can parse your xml document like a normal string, find information tag with regular expression and change it.

xml = xml.replace(/<information>[a-z0-9_-]*<\/information\>/, '<information>example</information>');

2)You can use some module, like xmldoc, to parse the document. https://github.com/nfarina/xmldoc

let xmldoc = require('xmldoc');
let document = new xmldoc.XmlDocument(data.toString());
document.descendantWithPath('information').val = "example";

Upvotes: 0

CaptainJ
CaptainJ

Reputation: 174

I would use cherriojs https://github.com/cheeriojs/cheerio .

Itis the nodejs implemetation of jQuery so DOM manipulations are easy. At the top of your file you have to set the xmlMode:true after you require it.

var $ = cheerio.load(your-xml-doc, {
          xmlMode: true
        });

Then you can use something like

$('information').text('example');

Upvotes: 1

Related Questions