Java 从html中提取文本:寻找一个好的类似sax的解析器或使用dom解析器的建议
我有一个html文档,格式如下:Java 从html中提取文本:寻找一个好的类似sax的解析器或使用dom解析器的建议,java,android,Java,Android,我有一个html文档,格式如下: <p> some plain text <em>some emphatized text</em>, <strong> some strong text</strong> </p> <p> just some plain text </p> <p> <strong>strong text </p> followed by p
<p>
some plain text <em>some emphatized text</em>, <strong> some strong text</strong>
</p>
<p>
just some plain text
</p>
<p>
<strong>strong text </p> followed by plain, <a>with a link at the end!</a>
</p>
出于这个目的,我想一个类似sax的解析器会比dom更好,因为我不知道内部标记的编号和顺序:一个段落可以有零个或多个不同类型的内部标记。您可以使用dom解析器,获取p标记内部的文本(包括子html元素)输入一个字符串变量,并使用其他一些功能从结果字符串中去除所有html标记。这将使您拥有p标记之间的所有内容,而没有任何子元素标记 示例
<p>
some plain text <em>some emphatized text</em>, <strong> some strong text</strong>
</p>
<p>
just some plain text
</p>
<p>
<strong>strong text </p> followed by plain, <a>with a link at the end!</a>
</p>
一些纯文本一些强调文本,一些强文本
只是一些纯文本
强文本后跟纯文本,末尾有链接!
使用一些dom解析器将p标记提取到字符串中,您将得到如下字符串:
String content = "some plain text <em>some emphatized text</em>, <strong> some strong text</strong>";
content = stripHtmlTags( content );
println( content ); // some plain text some emphatized text, some strong text
String content=“一些纯文本一些强调文本,一些强文本”;
content=stripHtmlTags(content);
println(内容);//一些纯文本,一些强调文本,一些强文本
String extractedText=Html.fromHtml(您的Html字符串).toString()
这将为您提供提取的文本。。
希望这对您有所帮助。添加代码以通过DOM pase读取CDATA
Add code to read CDATA by DOM pase
**childNode.getNodeType() == Node.CDATA_SECTION_NODE**
if Using XMLUtils modify like
public static String getNodeValue(Node node) {
node.normalize();
String response = node.getNodeValue();
if (response != null) {
return response;
} else {
NodeList list = node.getChildNodes();
int size = list == null ? 0 : list.getLength();
for (int j = 0; j < size; j++) {
Node childNode = list.item(j);
if (childNode.getNodeType() == Node.TEXT_NODE
|| childNode.getNodeType() == Node.CDATA_SECTION_NODE) {
response = childNode.getNodeValue();
return response;
}
}
}
return "";
}
**childNode.getNodeType()==Node.CDATA\u节\u节点**
如果使用XMLUtils,请进行类似的修改
公共静态字符串getNodeValue(节点){
node.normalize();
字符串响应=node.getNodeValue();
if(响应!=null){
返回响应;
}否则{
NodeList list=node.getChildNodes();
int size=list==null?0:list.getLength();
对于(int j=0;j
mm…我需要一个正则表达式,上面写着“extract everything is between to”,但我不是很好…你能帮我吗?
Add code to read CDATA by DOM pase
**childNode.getNodeType() == Node.CDATA_SECTION_NODE**
if Using XMLUtils modify like
public static String getNodeValue(Node node) {
node.normalize();
String response = node.getNodeValue();
if (response != null) {
return response;
} else {
NodeList list = node.getChildNodes();
int size = list == null ? 0 : list.getLength();
for (int j = 0; j < size; j++) {
Node childNode = list.item(j);
if (childNode.getNodeType() == Node.TEXT_NODE
|| childNode.getNodeType() == Node.CDATA_SECTION_NODE) {
response = childNode.getNodeValue();
return response;
}
}
}
return "";
}