0

現在、XML インクルージョンを含む xml リソース ファイルがあります。

stream = Main.class.getResourceAsStream("resource/Resource.xml");

xml ファイル内:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://www.w3.org/1999/xhtml"
      xmlns:xi="http://www.w3.org/2001/XInclude">   
    <element />
    <xi:include href="resource/1.xml"/>
</semantics>

ただし、解析後Resource.xml、含まれているファイルが存在しないというエラーが表示されます。

確認したところ、パスがプロジェクトのルート ディレクトリに連結されているように見えますが、1.xml後でリソース ファイルが jar ファイル内にあることが問題です。

DocumentBuilderto load をリソースとして含めることは可能ですか?

4

1 に答える 1

3

が処理されたときに正しい値を返すことができるように、カスタムを設定する必要がありEnitityResolver2ます。DocumentBuilderInputSourcexi:include

final DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new EntityResolver2() {
    @Override
    public InputSource getExternalSubset(String string, String string1) throws SAXException, IOException {
        return null;
    }

    @Override
    public InputSource resolveEntity(String string, String string1, String string2, String string3) throws SAXException, IOException {
        final String resourceName = string3;
        final InputSource is = new InputSource();
        is.setSystemId(resourceName);
        is.setByteStream(Thread.currentThread().getContextClassLoader().getResourceAsStream(resourceName));
        return is;
    }


    @Override
    public InputSource resolveEntity(String string, String string1) throws SAXException, IOException {
        return null;
    }
});

これにより、クラスローダーによってロードされたリソースの がInputSource返されます。正しいパスを取得するにはInputStream、 を操作する必要がある場合があります。String

于 2013-08-11T09:22:21.027 に答える