Condition 1
在使用 JAXB 编组时错如下,
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"bussinessServices"). Expected elements are <{http://fdframework.neusoft.com/config/bussinessServices}bussinessServices>
...
JAXB 使用代码如下,
InputStream inputStream = new FileInputStream("xxx.xml");
Object obj = JAXBUtil.unmarshal("com.xxx.fdframework.config.bussinessServices",inputStream);
对应 xsd 文件头部如下,
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://fdframework.xxx.com/config/bussinessServices"
xmlns:tns="http://fdframework.xxx.com/config/bussinessServices"
elementFormDefault="qualified">
对应 xml 文件头部如下,
<?xml version="1.0" encoding="UTF-8"?>
<bussinessServices>
Solution
有如下三种方法
a. 向对应的 XML 文件中添加命名空间;
b. 从 JAXB 映射中去除命名空间原数据,用包级别注解 @XmlSchema 指定;
参考链接:http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
c. 使用 XmlFilter 应用正确的命名空间信息在当前的 XML 文件中。
参考链接:JAXB unmarshal with declared type does not populate the resulting object with data
此处选择了第一种方法,即修改对应的 XML 文件头部如下,
<?xml version="1.0" encoding="UTF-8"?>
<bussinessServices xmlns="http://fdframework.xxx.com/config/bussinessServices" >
Reason
unresolved
补充
Condition 2
在使用 JAXB 进行 XML 反序列化操作时,错误提示如下,
javax.xml.bind.UnmarshalException: unexpected element (uri:"http://fdframework.xxx.com/config/messageConfig", local:"configuration"). Expected elements are (none)
...
对应 xsd 的配置文件片段如下,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://fdframework.xxx.com/config/messageConfig"
targetNamespace="http://fdframework.xxx.com/config/messageConfig">
<complexType name="configuration">
<sequence>
<element name="configItem" type="tns:configItem" maxOccurs="unbounded"
minOccurs="0"></element>
</sequence>
</complexType>
...
对应的配置中不包含任何 <element> 元素。
对应 ObjectFacotry 中的代码片段如下,
@XmlRegistry
public class ObjectFactory {
public ObjectFactory() {
}
...
}
Solution
修改对应 xsd 配置文件为如下,
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://fdframework.neusoft.com/config/messageConfig"
targetNamespace="http://fdframework.neusoft.com/config/messageConfig">
<element name="configuration" type="tns:configuration"></element>
<complexType name="configuration">
<sequence>
<element name="configItem" type="tns:configItem" maxOccurs="unbounded"
minOccurs="0"></element>
</sequence>
</complexType>
...
即添加了一个 <element> 元素作为根元素。
修改 xsd 文件后,查看生成类的代码,其中 ObjectFactory 中添加了一个静态变量常量如下,
@XmlRegistry
public class ObjectFactory {
private final static QName _Configuration_QNAME = new QName("http://fdframework.xxx.com/config/messageConfig", "configuration");
public ObjectFactory() {
}
...
}
Reason
unresolved