获取Java中不是html的字符串的一部分

时间:2013-04-24 14:43:20

标签: java html string parsing substring

在我的Java应用程序中,我有必须编辑的String。问题是这些字符串可以包含HTML标记/元素,不应该编辑它们(没有id来检索元素)。

场景(添加 - ):

String a = "<span> <table> </table>  </span> <div></div> <div> text 2</div>";
should become: <span> <table> </table>  </span> <div></div> <div> -text 2</div>  

String b = "text";
should become: -text

String c = "<p> t </p>";
should become: <p> -t </p>  

我的问题是:如何在包含html标签的字符串中检索文本(无法添加id或类)

1 个答案:

答案 0 :(得分:3)

您可以使用XML解析库。

String newText = null;
for ( Node node : document.nodes() ) {
  if ( node.text() != null ) newText = "-" + node.text();
}

请注意,这是伪的。

newText现在为-text或节点文本。

修改 对于“可以包含html元素的文字”,您的问题有点含糊不清 如果它不包含html标签,那么就不能使用XML解析器,这会提出问题..如果包含标签,那么为什么你不能这样做......

String newString = "-" + a;