我在应用程序中看到,解析的XML文件中的xinclude在Java XSLT转换中不起作用。

但是,尽管我这样做:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setXIncludeAware(true);


我没有专门设置变压器工厂,因为System.getProperty("javax.xml.transform.TransformerFactory")返回“ null”。

我的问题:默认Java(1.6或6)是否支持xinclude,还是必须添加替代XSLT解析器(如Apache Xerces)?

最佳答案

根据the spec的说法,从Java 1.5(5)开始就存在支持。我相信XInclude支持依赖于namespace awareness,由于向后兼容的原因,默认情况下将其关闭。

public class XIncludeDemo {

    private static final String XML = "<?xml version=\"1.0\"?>\n"
            + "<data xmlns=\"foo\" xmlns:xi=\"http://www.w3.org/2001/XInclude\">\n"
            + "<xi:include href=\"include.txt\" parse=\"text\"/>\n"
            + "</data>\n";

    private static final String INCLUDE = "Hello, World!";

    public static void main(String[] args) throws Exception {
        // data
        final InputStream xmlStream = new ByteArrayInputStream(XML
                .getBytes("UTF-8"));
        final InputStream includeStream = new ByteArrayInputStream(INCLUDE
                .getBytes("UTF-8"));
        // document parser
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setXIncludeAware(true);
        factory.setNamespaceAware(true);
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        if (!docBuilder.isXIncludeAware()) {
            throw new IllegalStateException();
        }
        docBuilder.setEntityResolver(new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (systemId.endsWith("include.txt")) {
                    return new InputSource(includeStream);
                }
                return null;
            }
        });
        Document doc = docBuilder.parse(xmlStream);
        // print result
        Source source = new DOMSource(doc);
        Result result = new StreamResult(System.out);
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(source, result);
    }

}

09-30 15:15