在相对路径上解析具有DTD架构的XML文件 [英] Parsing an XML file with a DTD schema on a relative path

查看:320
本文介绍了在相对路径上解析具有DTD架构的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下java代码:

I have the following java code:



DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(new File("/opt/myfile"));

/ opt / myfile 包含类似的内容:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE archive SYSTEM "../../schema/xml/schema.dtd">
...

我收到以下错误:


java.io.FileNotFoundException: /../schema/xml/schema.dtd (No such file or directory)

这是一个大型java框架,它使用其他地方生成的XML文件。我认为相对路径是问题所在。我不认为在JVM启动之前更改cwd是可以接受的(路径来自JVM本身读取的配置文件)并且我没有找到在JVM运行时更改cwd的方法。如何使用适当的DTD解析此XML文件?

This is a large java framework that consumes an XML file produced elsewhere. I think the relative path is the problem. I don't think it will be acceptable to change the cwd before the JVM starts (the path comes from a config file that is read by the JVM itself) and I have not found a way to change the cwd while the JVM is running. How do I parse this XML file with the appropriate DTD?

推荐答案

您需要使用自定义 EntityResolver 调整DTD的路径,以便找到它。例如:

You need to use a custom EntityResolver to tweak the path of the DTD so that it can be found. For example:

db.setEntityResolver(new EntityResolver() {
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
        if (systemId.contains("schema.dtd")) {
            return new InputSource(new FileReader("/path/to/schema.dtd"));
        } else {
            return null;
        }
    }
});

如果 schema.dtd 在您的类路径上,您只需使用 getResourceAsStream 加载它,而无需指定完整路径:

If schema.dtd is on your classpath, you can just use getResourceAsStream to load it, without specifying the full path:

return new InputSource(Foo.class.getResourceAsStream("schema.dtd"));

这篇关于在相对路径上解析具有DTD架构的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆