0

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.

Vishu
  • 1,105
  • 3
  • 10
  • 19

1 Answers1

2

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)
   })
}); 
shivshankar
  • 2,067
  • 1
  • 18
  • 28
  • i dont want to replace as my file has lot of content. I just wanted to append new shell tag after last shell tag found in xml. – Vishu Nov 25 '17 at 08:06
  • are you sure file have only one tag or what you want to append after particular tag – shivshankar Nov 25 '17 at 08:18
  • i have 4 to 5 different shell tags in my file, and i wanted to create a new shell tag and append it after the last shell tag i found in xml file. – Vishu Nov 25 '17 at 08:29
  • is lastIndexof and replace are functions associateed with data in nodejs, as its giving me error as data.lastIndexof is not function – Vishu Nov 25 '17 at 09:07
  • sorry it it is lastIndexOf pls check again – shivshankar Nov 25 '17 at 09:09
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/159797/discussion-between-vishu-and-shivshankar). – Vishu Nov 25 '17 at 09:19
  • check @Vishu. it's a patch not general purpose solution – shivshankar Nov 25 '17 at 10:04