2013-06-04 116 views
5

我想創建一個使用XInclude通過JAXB解組的xml文檔的組合xml文檔。「嘗試解析XML文件時出錯」使用XInclude解析時

這裏是我的解組代碼:

@Override 
public T readFromReader(final Reader reader) throws Exception { 
    final Unmarshaller unmarshaller = createUnmarshaller(); 

    final SAXParserFactory spf = SAXParserFactory.newInstance(); 
    spf.setXIncludeAware(true); 
    spf.setNamespaceAware(true); 
    //spf.setValidating(true); 

    final XMLReader xr = spf.newSAXParser().getXMLReader(); 

    final SAXSource source = new SAXSource(xr, new InputSource(reader)); 

    try { 
     final T object = (T) unmarshaller.unmarshal(source); 
     postReadSetup(object); 
     return object; 
    } catch (final Exception e) { 
     throw new RuntimeException("Cannot parse XML: Additional information is attached. Please ensure your XML is valid.", e); 
    } 
} 

這裏是我的主XML文件:

<?xml version="1.0" encoding="UTF-8" ?> 
<tag1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xi="http://www.w3.org/2001/XInclude" 
       xsi:schemaLocation="path-to-schema/schema.xsd"> 

    <xi:include href="path-to-xml-files/included.xml"></xi:include> 
</tag1> 

而且included.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<tag2> Some text </tag2> 

爲了真正解組吧,我用我的xml文件的路徑創建一個新的FileReader(path-to-xml-files/main.xml - 路徑是cor因爲它可以清楚地找到主文件)。但是,當我運行它時,包含的文件有問題。我得到一個帶有這個錯誤信息的鏈接SAXParseException的UnmarshalException:試圖解析XML文件(href ='path-to-xml-files/included.xml')時出錯。

當我手動將included.xml的內容合併到main.xml中時,它運行時沒有問題。

我不能說這是JAXB問題還是XInclude問題,但我強烈懷疑後者。

我錯過了什麼?

回答

2

我這個完全一樣的問題打了三個小時,終於我發現這一點:

xerces.apache.org/xerces2-j/features.html

總之,你需要添加下面一行:

spf.setFeature(」 http://apache.org/xml/features/xinclude/fixup-base-uris 「,假);

+1

此網址不存在......也許你可以參考官方消息:http://xerces.apache.org/xerces2-j/features.html – devyndraen

+0

我有相同的方法,並將SaxParserFactory功能'http:// apache.org/xml/features/xinclude/fixup-base-uris'設置爲false在這裏沒有幫助。任何其他成功的人呢? –

0

我有完全相同的問題。 其實,href屬性期待一個URI,它可以是:

  • HTTP地址(這意味着你的XML包含必須某處託管)
  • 或者你的本地計算機上的文件。但是在這種情況下,你需要用「file:...」作爲前綴並提供絕對路徑。

你的榜樣:

<?xml version="1.0" encoding="UTF-8" ?> 
<tag1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xi="http://www.w3.org/2001/XInclude" 
       xsi:schemaLocation="path-to-schema/schema.xsd"> 

    <xi:include href="file:absolute-path-to-xml-files/included.xml"/> 
</tag1>