Vishu
Vishu

Reputation: 1125

How to append element after particular element in nodejs

My .XMl is

<?xml version="1.0" encoding="utf-8"?>

<data>
    <shell id="TX-alg1-title">Lesson 2.1</shell>
    <options id="parent">
        <option id="TX-alg1">TX16E_ISE_0005</option>
        <option id="TX-alg1-CID">9780353053</option>
    </options>	
</data>

I wanted to add another shell tag after shell tag previously present in xml.

Expected O/p

<?xml version="1.0" encoding="utf-8"?>

<data>
    <shell id="TX-alg1-title">Lesson 2.1</shell>
    <shell id="CA-int1-title">Lesson 2.1</shell>
    <options id="parent">
        <option id="TX-alg1">TX16E_ISE_0005</option>
        <option id="TX-alg1-CID">9780353053</option>
    </options>	
</data>

I am reading my .XML file in app.js as

fs.readFile( './dlo_custom_en-US.xml', function(err, data) {
    
});

Please advise how to append shell tag after already present shell tag in nodejs.

Upvotes: 0

Views: 385

Answers (1)

shivshankar
shivshankar

Reputation: 2135

question is almost similar Regex match text between tags node is noting except javascript at server side. almost all programming languages have regexp to find patterns. here is simplest solution but you should to study more about regexp

fs.readFile( './dlo_custom_en-US.xml', function(err, data) {
    data.replace(/\<shell(.)*\<\/shell>/, "new replacement here")
}); 

***** updated ***** from JavaScript: How can I insert a string at a specific index

var fs =require('fs')
String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

fs.readFile( './dlo_custom_en-US.xml',"utf8", function(err, data) {
  if(err) return 
   var index  = data.lastIndexOf('</shell>')+8
   console.log(index)
  var data=   data.splice(index,0, 'newwwwwwwwwww')
   console.log(data)
   fs.writeFile('./new.xml',data,(err, done)=>{
    if(err) return 
    console.log(err, done)
   })
}); 

Upvotes: 2

Related Questions