gpt4 book ai didi

java - 如何在特定字符串中查找字符串并插入

转载 作者:行者123 更新时间:2023-12-02 12:50:57 26 4
gpt4 key购买 nike

我有一个获取 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 之前添加,而不仅仅是第一个,所以我们得到无限循环。我怎样才能做到这一点?

最佳答案

使用 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>

关于java - 如何在特定字符串中查找字符串并插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44614020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com