2017-06-18 38 views
0

我有一個獲取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之前,不僅是第一個,所以我們得到無限循環。我怎樣才能做到這一點?

+0

你應該用正則表達式來做到這一點。 –

+0

但是在這裏我需要添加一些東西,而不是替換 –

回答

0

這裏所提出的soliution是一個非常簡單的一個:通過標記名拆分輸入,然後加入拼湊和插入的註釋和標記名。

public static String addCommentXML(String xmlString, String tagName, String comment) 
{ 
    String[] parts = xmlString.split("\\Q<" + tagName + ">\\E"); 
    String output = parts[0]; 
    for (int i = 1 ; i < parts.length ; i++) { 
     output += comment + "<" + tagName + ">" + parts[i]; 
    } 
    return output; 
} 

親:沒有第三方的lib需要
騙子:這種方法並沒有真正解析XML,因此,有時會產生erronous結果(如果標籤被發現裏面像評論...)

1

它可以很容易地與JSOUP庫完成。這是使用HTML/XML的完美工具。

https://jsoup.org/

https://mvnrepository.com/artifact/org.jsoup/jsoup/1.10.3

在你的情況它看起來就像這樣:

public static void main(String[] args) { 
    String processedXml = addCommentXML(getDocument(), "second", "it's a comment"); 
    System.out.println(processedXml); 
} 

private static String addCommentXML(String xmlString, String tagName, String comment) { 
    Document document = Jsoup.parse(xmlString); 
    document.getElementsByTag(tagName).before("<!--" + comment + "-->"); 
    return document.toString(); 
} 

private static String getDocument() { 
    return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + 
      "<first>\n" + 
      "<second>some string</second>\n" + 
      "<second>some string</second>\n" + 
      "<second><![CDATA[need CDATA because of <and>]]></second>\n" + 
      "<second/>\n" + 
      "</first>"; 
} 

輸出

<html> 
 
<head></head> 
 
<body> 
 
    <first> 
 
    <!--it's a comment--> 
 
    <second> 
 
    some string 
 
    </second> 
 
    <!--it's a comment--> 
 
    <second> 
 
    some string 
 
    </second> 
 
    <!--it's a comment--> 
 
    <second> 
 
    need CDATA because of &lt; and &gt; 
 
    </second> 
 
    <!--it's a comment--> 
 
    <second /> 
 
    </first> 
 
</body> 
 
</html>

相關問題