J'ai une méthode qui obtient une chaîne XML et, en théorie, doit insérer un commentaire avant CHAQUE étiquette particulière. Je me demande comment faire fonctionnerComment trouver une chaîne à l'intérieur d'une chaîne particulière et insérer
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();
}
Sortie de addCommentXML("somereallylongxml", "second", "it’s a comment")
devrait être
<?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>
Mais il ne semble pas le problème, car je ne sais pas comment itérer à travers la chaîne correctement à ajouter avant CHAQUE tagName, pas seulement en premier, donc on obtient une boucle infinie. Comment puis je faire ça?
vous devriez le faire avec une expression régulière. –
Mais ici, je dois ajouter quelque chose avant de ne pas remplacer –