0

Hi have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
    <library>
    <item>
    <books> 
        <?xml version="1.0" encoding="UTF-8"?>
            &lt;Fiction&gt;
            &lt;tt:Author&gt;A&lt;/tt:Author&gt;
            &lt;tt:BookName&gt;45&lt;/tt:BookName&gt;
            &lt;/Fiction&gt;
    </books>
    </item>
    </library>

I want to basically replace the second occurence of the entire xml tag with blank space. So basically replace <?xml version="1.0" encoding="UTF-8"?> string which appears after the <books> opening tag with a space.

Any suggestions? I tried other links but could not get a working solution. The problem is there are ", ? and > in between the xml tag and the string replace function is considering that as an escape sequence character.

This is what I tried:

var stringToReplace = '<?xml version="1.0" encoding="UTF-8"?>';
   var string = data.string;
   //console.log(string);
    var t=0;   
    var text = string.replace(/stringToReplace/g, function (match) {
    t++;

    return (t === 2) ? "Not found" : match;
    });
console.log(text);

The above still prints both the xml tags

Aman Mohammed
  • 2,878
  • 5
  • 25
  • 39

1 Answers1

0

Assuming your XML always looks like this, you can use regular String methods to find the last occurrence of the string and remove it by creating substrings of the XML around it:

 const xml = `<?xml version="1.0" encoding="UTF-8"?>
    <library>
    <item>
    <books> 
        <?xml version="1.0" encoding="UTF-8"?>
            &lt;Fiction&gt;
            &lt;tt:Author&gt;A&lt;/tt:Author&gt;
            &lt;tt:BookName&gt;45&lt;/tt:BookName&gt;
            &lt;/Fiction&gt;
    </books>
    </item>
    </library>`;
const strToReplace = '<?xml version="1.0" encoding="UTF-8"?>';
const index = xml.lastIndexOf(strToReplace);

// The new left- and right-sides of the string will omit the strToReplace
const newXml = xml.substring(0, index) + xml.substring(index + strToReplace.length);
console.log(newXml);
skyline3000
  • 7,639
  • 2
  • 24
  • 33