2009-02-24 18 views
8

Tôi thấy trong ứng dụng của tôi rằng xinclude bên trong tệp XML được phân tích cú pháp của tôi không hoạt động trong chuyển đổi Java XSLT của tôi.Hỗ trợ mặc định cho xinclude trong Java 6?

Tuy nhiên, mặc dù tôi làm:

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

Tôi không thiết lập đặc biệt là nhà máy biến áp như System.getProperty("javax.xml.transform.TransformerFactory") lợi nhuận "vô giá trị".

Câu hỏi của tôi: hỗ trợ Java (1.6 hoặc 6) mặc định xinclude hoặc tôi có phải thêm trình phân tích cú pháp XSLT thay thế như Apache Xerces không?

Trả lời

13

Theo the spec, hỗ trợ đã có từ Java 1.5 (5). Tôi tin rằng hỗ trợ XInclude dựa trên namespace awareness, được tắt theo mặc định vì lý do tương thích ngược.

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); 
    } 

} 
+0

Cảm ơn bạn đã cung cấp thông tin. Tôi sẽ cần một chút thời gian để áp dụng nó và xem liệu tôi có thể chấp nhận nó hay không. Thông tin bạn đưa cho tôi là những gì tôi cần. – Roalt

+1

Cảm ơn, chỉ là những gì tôi đang tìm kiếm! –