5

我正在尝试使用 XInclude 创建一个组合的 xml 文档,以便通过 JAXB 解组。

这是我的解组代码:

@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>

并包含.xml:

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

为了真正解组它,我FileReader用我的 xml 文件的路径创建了一个新文件(path-to-xml-files/main.xml - 路径是正确的,因为它可以清楚地找到主文件)。但是,当我运行它时,包含的文件有问题。我收到带有链接 SAXParseException 的 UnmarshalException 并带有以下错误消息:尝试解析 XML 文件时出错 (href='path-to-xml-files/included.xml')。

当我手动将included.xml 的内容合并到main.xml 中时,它运行没有问题。

我不知道这是 JAXB 问题还是 XInclude 问题,但我强烈怀疑是后者。

我错过了什么?

4

2 回答 2

2

我与这个完全相同的问题斗争了三个小时,最后我发现了这个:

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

简而言之,您需要添加以下行:

spf.setFeature(" http://apache.org/xml/features/xinclude/fixup-base-uris ", false);

于 2013-09-19T23:10:08.737 回答
0

I had the exact same issue. Actually, the href attribute expects an URI, which can be:

  • Either an HTTP address (which means your included XML must be hosted somewhere)
  • Or a file on your local machine. But in that case, you need to prefix it with "file:..." and provide the absolute path.

With your example:

<?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>
于 2017-11-23T15:20:35.380 回答