我有一个获取XML字符串的方法,理论上应该在每个特定标记之前插入注释。我不知道如何使它工作如何查找特定字符串内的字符串并插入
public static String addCommentXML(String xmlString, String tagName, String comment)
{
StringBuilder sb = new StringBuilder(xmlString);
for(int i = 0; i < sb.toString().length(); i++)
{
if(sb.toString().toLowerCase().contains("<"+tagName+">"))
{
sb.insert(sb.toString().indexOf("<"+tagName+">", i) - 1, "<!--"+ comment+"-->"+"\n");
}
}
return sb.toString();
}
的addCommentXML("somereallylongxml", "second", "it’s a comment")
输出应该
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<first>
<!--it's a comment-->
<second>some string</second>
<!--it's a comment-->
<second>some string</second>
<!--it's a comment-->
<second><![CDATA[need CDATA because of <and>]]></second>
<!--it's a comment-->
<second/>
</first>
但它显然是行不通的,因为我不知道如何通过遍历字符串正确添加在每个tagName之前,不仅是第一个,所以我们得到无限循环。我怎样才能做到这一点?
你应该用正则表达式来做到这一点。 –
但是在这里我需要添加一些东西,而不是替换 –