2016-07-23 129 views
1

我想解析的只是包含尖括号作为文本一部分的html文档的文本。如何防止Jsoup在解析文本时擦除文本中的尖括号

例如,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,非常感谢任何形式的帮助。 谢谢。

+0

您的HTML似乎无效。请看看[这个答案](http://stackoverflow.com/a/10462413/1992780)。 –

+1

谢谢你的评论!我想一个好的开始就是遍历元素,并在开始解析之前将文本中的“<”字符转换为“<”。 – Joon

回答

0

由于达维德帕斯托雷的评论,这个问题“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); 
    } 
} 

如果你通过你开始解析之前在文本转换“<”到<的过程中,你将能够在得到正确的输出。