“尝试解析XML文件时出错”使用XInclude解析时

问题描述:

我想创建一个使用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问题,但我强烈怀疑后者。

我错过了什么?

我这个完全一样的问题打了三个小时,终于我发现这一点:

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在这里没有帮助。任何其他成功的人呢? –

我有完全相同的问题。 其实,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>