Hi有以下xml:
<?xml version="1.0" encoding="UTF-8"?>
<library>
<item>
<books>
<?xml version="1.0" encoding="UTF-8"?>
<Fiction>
<tt:Author>A</tt:Author>
<tt:BookName>45</tt:BookName>
</Fiction>
</books>
</item>
</library>
我想基本上用空格替换整个xml标记的第二次出现。因此,基本上将出现在<books>
打开标记之后的<?xml version="1.0" encoding="UTF-8"?>
字符串替换为空格。
有什么建议吗?我尝试了其他链接,但无法获得有效的解决方案。问题是在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标签
假设您的XML总是这样,您可以使用常规的String方法来查找字符串的最后一次出现,并通过在其周围创建XML的子字符串来删除它:
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<library>
<item>
<books>
<?xml version="1.0" encoding="UTF-8"?>
<Fiction>
<tt:Author>A</tt:Author>
<tt:BookName>45</tt:BookName>
</Fiction>
</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);