解析内部<p>标签

时间:2015-08-14 10:06:35

标签: java string xml-parsing

我需要解析xml内容,需要在

中找到内部标签
<p><span>test</span></p> <p><span>test12</span></p>  <p>Some text<p><span>test</span></p></p>

在我的上述测试中,最后一个p标签内部有p标签。我需要找到p标签的内部p标签。我尝试如下

public static void main(String[] args) {
  String  text= "<p><span>test</span></p> <p><span>test12</span></p>  <p>Some text<p><span>test</span></p></p>";
  Pattern pattern = Pattern.compile("<p>.*?</p>");
  Matcher matcher = pattern.matcher(text);
  while (matcher.find()) {
    String match = matcher.group();
    //System.out.println("matcher group:"+match);
    if (match.lastIndexOf("<p>") > 0) {
            //System.out.println("Substring:"+match.substring(match.indexOf("<p>") + "<p>".length(), match.indexOf("</p>")));
            text = text.replace(match, "<p>" +match.substring(match.indexOf("<p>") + "<p>".length(), match.indexOf("</p>")).replaceAll("<p>", ""));
        }
    }
 System.out.println("text:"+text);
}

如果有任何简单的方法,请告诉我。

1 个答案:

答案 0 :(得分:0)

查看JAXB

正如其他人所建议的那样,不要手动执行此操作,而是使用现有的库,如JAXB。

可以找到一个易于理解的JAXB hello world示例here

相关问题