我正在尝试使用 EclipseLink MOXy 解析一些 XML,但它在 xsi
属性行上失败了。如果我删除它,它会很好地解析。但是,我有 100GiB 的 XML 需要处理,更改源文件不是一个选项。
有人建议,如果我可以设置 XmlParser.setNamespaceAware(false)
那么它应该可以工作 - 但我不知道如何配置它,而不是直接进入 MOXy 的内部。
<record>
<header>
<!-- citation-id: 14404534; type: journal_article; -->
<identifier>info:doi/10.1007/s10973-004-0435-2</identifier>
<datestamp>2009-04-28</datestamp>
<setSpec>J</setSpec>
<setSpec>J:1007</setSpec>
<setSpec>J:1007:2777</setSpec>
</header>
<metadata>
<crossref xmlns="http://www.crossref.org/xschema/1.0"
xsi:schemaLocation="http://www.crossref.org/xschema/1.0 http://www.crossref.org/schema/unixref1.0.xsd">
<journal>
<journal_metadata language="en">
[...]
当存在 xsi:
前缀时我得到的异常是:
org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[Exception [EclipseLink-25004] (Eclipse Persistence Services - 2.4.0.v20120608-r11652): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred unmarshalling the document
Internal Exception: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[13,107]
Message: http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributePrefixUnbound?crossref&xsi:schemaLocation&xsi]
最佳答案
目前 EclipseLink JAXB (MOXy) 中没有选项告诉它忽略命名空间。但是有一种方法可以通过利用 StAX 解析器来使用。
演示
您可以在不识别命名空间的 XML 输入上创建一个 StAX XMLStreamReader
,然后让 MOXy 从中解码。
package forum13416681;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
StreamSource source = new StreamSource("src/forum13416681/input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(source);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Foo root = (Foo) unmarshaller.unmarshal(xsr);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(root, System.out);
}
}
Java 模型(Foo)
package forum13416681;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Foo {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
输入(input.xml)
以下是您问题中 XML 的简化版本。请注意,此 XML 未正确限定命名空间,因为它缺少 xsi 前缀的命名空间声明。
<?xml version="1.0" encoding="UTF-8"?>
<foo xsi:schemaLocation="http://www.crossref.org/xschema/1.0 http://www.crossref.org/schema/unixref1.0.xsd">
<bar>Hello World</bar>
</foo>
输出
下面是运行演示代码的输出。
<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar>Hello World</bar>
</foo>
关于java - 如何将命名空间感知设置为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13416681/