【发布时间】:2015-06-19 19:11:21
【问题描述】:
我使用 Jaxb2 和 Spring。我正在尝试解组我的两个客户发送的一些 XML。
到目前为止,我只需要处理一个客户,它发送了一些这样的 xml:
<foo xmlns="com.acme">
<bar>[...]</bar>
<foo>
像这样绑定到 POJO:
@XmlType(name = "", propOrder = {"bar"})
@XmlRootElement(name = "Foo")
public class Foo {
@XmlElement(name = "Bar")
private String bar;
[...]
}
我发现之前的开发人员在解组器中对命名空间进行了硬编码,以使其正常工作。
现在,第二个客户发送了相同的 XML,但更改了命名空间!
<foo xmlns="com.xyz">
<bar>[...]</bar>
<foo>
很明显,解组器无法解组,因为它需要一些{com.acme}foo 而不是{com.xyz}foo。不幸的是,要求客户更改 XML 不是一种选择。
我尝试了什么:
1) 在application-context.xml 中,我搜索了一种可以让我忽略命名空间但找不到的配置:
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="packagesToScan">
<list>
<value>com.mycompany.mypkg</value>
</list>
</property>
<property name="marshallerProperties">
<map>
<entry key="???"><value type="java.lang.Boolean">false</value></entry>
</map>
</property>
</bean>
似乎唯一可用的选项是 Jaxb2Marshaller 的 Javadoc 中列出的选项:
/**
* Set the JAXB {@code Marshaller} properties. These properties will be set on the
* underlying JAXB {@code Marshaller}, and allow for features such as indentation.
* @param properties the properties
* @see javax.xml.bind.Marshaller#setProperty(String, Object)
* @see javax.xml.bind.Marshaller#JAXB_ENCODING
* @see javax.xml.bind.Marshaller#JAXB_FORMATTED_OUTPUT
* @see javax.xml.bind.Marshaller#JAXB_NO_NAMESPACE_SCHEMA_LOCATION
* @see javax.xml.bind.Marshaller#JAXB_SCHEMA_LOCATION
*/
public void setMarshallerProperties(Map<String, ?> properties) {
this.marshallerProperties = properties;
}
2) 我也尝试在代码中配置解组器:
try {
jc = JAXBContext.newInstance("com.mycompany.mypkg");
Unmarshaller u = jc.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);//Tried this option.
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile.toFile());
u.unmarshal(new DOMSource(doc));
return (Foo)u.unmarshal(new StreamSource(xmlFile.toFile()));
} catch (ParserConfigurationException | SAXException | IOException | JAXBException e) {
LOGGER.error("Erreur Unmarshalling CPL");
}
3) 使用 SAXParser 的不同形式:
try {
jc = JAXBContext.newInstance("com.mycompany.mypkg");
Unmarshaller um = jc.createUnmarshaller();
final SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(false);
final XMLReader reader = sax.newSAXParser().getXMLReader();
final Source er = new SAXSource(reader, new InputSource(new FileReader(xmlFile.toFile())));
return (Foo)um.unmarshal(er);
}catch(...) {[...]}
这个可行!但是,我仍然希望能够自动装配 Unmarshaller,而不需要每次都需要这个丑陋的配置。
【问题讨论】: