gpt4 book ai didi

java - Dom4j 解析 - 如何以编程方式声明 HTML 实体? "The entity "nbsp“已引用,但未声明。”

转载 作者:行者123 更新时间:2023-12-01 05:02:32 25 4
gpt4 key购买 nike

我正在使用 Dom4j 来解析 HTML 文档。Dom4j 需要 XML,因此不会声明 HTML 实体。可以在文档的 DTD 中声明它们,但我正在解析外部输入,所以这是不合适的。我宁愿在解析器中以编程方式声明它们。

这是我的代码:

    // Read.
final DocumentFactory df = DOMDocumentFactory.getInstance();
SAXReader reader = new SAXReader();
Document doc, outDoc;
try {
doc = reader.read( new StringReader(htmlStr) );
}
catch( Exception ex ){
throw new RuntimeException("Error parsing the HTML:\n " + ex.toString() );
}

我看到 SAXReaderreader.setEntityResolver( ??? ); 但似乎这不是解决方案,因为可重写方法如下所示:

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException

我正在寻找类似于

reader.setTrueEntityResolver( new EntityResolver(){
public InputStream resolve( String name ){ ... }
}

最佳答案

我在 http://evc-cit.info/dom4j/dom4j_groovy.html 中找到了可能的解决方案建议添加 XML Commons Catalog 内容。

但是,这似乎有点矫枉过正,因为无论如何都没有指定文档类型,而且我只想解析公共(public) HTML 4 实体。

更新:事实证明,如果没有显式的 DOCTYPE 声明,这不会产生任何效果 - EntityResolver 永远不会被调用。

Maven 部门:

    <dependency>
<groupId>xml-resolver</groupId>
<artifactId>xml-resolver</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>

在类路径上的 /CatalogManager.proeprties 中配置:

# allow location to be relative to this file's directory
relative-catalogs=yes

# A semicolon-delimited list of catalog files.
# In this instance, we have a single catalog file, and it's a relative path name
catalogs=sgml-lib/xml.soc

# no debugging messages, please
verbosity=0

# Use the SYSTEM identifier
prefer=system

告诉解析器在遇到 DTD 时使用目录解析器:

cResolver = new CatalogResolver( cMgr )
reader = new SAXReader( )
reader.setEntityResolver( cResolver )

关于java - Dom4j 解析 - 如何以编程方式声明 HTML 实体? "The entity "nbsp“已引用,但未声明。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13206774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com