我有一個獲取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之前,不僅是第一個,所以我們得到無限循環。我怎樣才能做到這一點?
你應該用正則表達式來做到這一點。 –
但是在這裏我需要添加一些東西,而不是替換 –