2017-06-18 37 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>

相关问题