【问题标题】:How to prevent Jsoup from erasing angle-brackets inside text when parsing解析时如何防止Jsoup擦除文本内的尖括号
【发布时间】:2016-11-27 01:26:48
【问题描述】:

我正在尝试仅解析包含尖括号作为文本一部分的 html 文档的文本。

例如,html 文件看起来像这样:

<html>
 <head></head> 
 <body> 
  <div>
    <p>1. <someUnicodeString></p> 
    <p>2. <foo 2012.12.26.></p> 
    <p>3. <123 2012.12.26.></p> 
    <p>4. <@ 2012.12.26.></p> 
    <p>5. foobarbar</p> 
  </div>
 </body>
</html>

我希望解析后的文本文件的结果是这样的:

1. <someUnicodeString> 
2. <foo 2012.12.26.> 
3. <123 2012.12.26.> 
4. <@ 2012.12.26.> 
5. foobarbar

我正在使用Jsoup的解析函数来实现这个,如下图所示,

Document doc = null;

try {
    doc = Jsoup.parse(new File(path), "UTF-8");
    doc.outputSettings(new Document.OutputSettings().prettyPrint(false));
    doc.outputSettings().escapeMode(EscapeMode.xhtml);

    //set line breaks in readable format
    doc.select("br").append("\\n");
    doc.select("p").prepend("\\n\\n");
    String bodyText = doc.body().html().replaceAll("\\\\n", "\n");
    bodyText = Jsoup.clean(bodyText, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));

    File f = new File(textFileName+".txt");
    f.getParentFile().mkdirs();
    PrintWriter writer = new PrintWriter(f, "UTF-8");
    writer.print(Parser.unescapeEntities(bodyText, false));
    writer.close();
} catch(IOException e) {
    //Do something
    e.printStackTrace();
}

但是,一旦 Jsoup 完成解析过程,它会为每个尖括号添加标签,后跟字符。

<p>1. <someUnicodeString></someUnicodeString></p> 
<p>2. <foo 2012.12.26.></foo></p> 
<p>3. <123 2012.12.26.></p> 
<p>4. <@ 2012.12.26.></p> 
<p>5. foobarbar</p> 

最终产生结果

1.  
2.  
3. <123 2012.12.26.> 
4. <@ 2012.12.26.> 
5. asdasd 

如何防止 Jsoup 在解析时擦除文本中的尖括号?

或者有没有办法让 Jsoup 识别某些尖括号不是 html 元素? (也许使用正则表达式?)

我是 Jsoup 的新手,非常感谢任何形式的帮助。 谢谢。

【问题讨论】:

  • 您的 HTML 似乎无效。请看this answer
  • 感谢您的评论!我想一个好的开始是遍历元素并将文本中的“

标签: java html jsoup


【解决方案1】:

感谢 Davide Pastore 的评论和问题“Right angle bracket in HTML

我能够使用以下代码解决问题。

doc = Jsoup.parse(new File(path), "UTF-8");
//replace all left-angle tags inside <p> element to "&lt;"
Elements pTags = doc.select("p");
for (Element tag : pTags) {
    //change the boundary of the regex to whatever suits you
    if (tag.html().matches("(.*)<[a-z](.*)")) {
        String innerHTML = tag.html().replaceAll("<(?=[a-z])", "&lt;");
        tag.html(innerHTML);
    }
}

如果您在开始解析之前将文本中的“<,您将能够获得正确的输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多