gpt4 book ai didi

java - 将 Doctype 作为 XML 文档解析 XHTML 文件的性能很糟糕

转载 作者:数据小太阳 更新时间:2023-10-29 02:24:33 25 4
gpt4 key购买 nike

当我将这个 xhtml 文件解析为 xml 时,对这样一个简单的文件进行解析大约需要 2 分钟。我发现如果我删除文档类型声明,它会立即解析。导致此文件解析时间过长的错误是什么?

Java 示例

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware( true );
DocumentBuilder bob = dbf.newDocumentBuilder();
Document template = bob.parse( new InputSource( new FileReader( xmlFile ) ) );

XHTML 范例

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ex="http://www.example.com/schema/v1_0_0">
<head><title>Test</title></head>
<body>
<h1>Test</h1>
<p>Hello, World!</p>
<p><ex:test>Text</ex:test></p>
</body>
</html>

谢谢

编辑:解决方案

为了根据所提供的有关问题最初发生原因的信息实际解决问题,我执行了以下基本步骤:

  1. 将 DTD 相关文件下载到 src/main/resources 文件夹
  2. 创建了一个自定义的 EntityResolver 以从类路径中读取这些文件
  3. 告诉我的 DocumentBuilder 使用我的新 EntityResolver

我在这样做时引用了这个 SO 答案:how to validate XML using java?

新的实体解析器

import java.io.IOException;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class LocalXhtmlDtdEntityResolver implements EntityResolver {

/* (non-Javadoc)
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
*/
@Override
public InputSource resolveEntity( String publicId, String systemId )
throws SAXException, IOException {
String fileName = systemId.substring( systemId.lastIndexOf( "/" ) + 1 );
return new InputSource(
getClass().getClassLoader().getResourceAsStream( fileName ) );
}

}

如何使用新的 EntityResolver:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware( true );
DocumentBuilder bob = dbf.newDocumentBuilder();
bob.setEntityResolver( new LocalXhtmlDtdEntityResolver() );
Document template = bob.parse( new InputSource( new FileReader( xmlFile ) ) );

最佳答案

Java 正在下载指定的 DTD 及其包含的文件,以验证您的 xhtml 文件是否遵守指定的 DTD。使用 Charles 代理,我记录了以下使用指定数量加载的请求:

关于java - 将 Doctype 作为 XML 文档解析 XHTML 文件的性能很糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628968/

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