JavaScript字符串替换XML中的第二次出现

嗨,您的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>

我想基本上用空格替换整个xml标记的第二次出现。因此,基本上将<?xml version="1.0" encoding="UTF-8"?>开头标记后面的<books>字符串替换为空格。

有什么建议吗?我尝试了其他链接,但无法获得有效的解决方案。问题是xml标记之间存在",? and >,字符串替换功能正在将其视为转义序列字符。

这是我尝试过的:

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);

上面仍然打印了两个xml标记

epavelly 回答:JavaScript字符串替换XML中的第二次出现

假设您的XML始终像这样,您可以使用常规的String方法查找该字符串的最后一次出现,并通过在其周围创建XML的子字符串来将其删除:

 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);

本文链接:https://www.f2er.com/3159050.html

大家都在问