我已经从WSDL文件生成了JAXB类,我尝试做的是将XML转换为Java对象。这里生成了JAXB类示例:
XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetProductListResponse", propOrder = {
"productList",
"productListDate",
"failed",
"failedDescription"
})
public class GetProductListResponse {
@XmlElementRef(name = "ProductList", namespace = "http://productService.productsdata", type = JAXBElement.class, required = false)
protected JAXBElement<ArrayOfProductListDetail> productList;
@XmlElementRef(name = "ProductListDate", namespace = "http://productService.productsdata", type = JAXBElement.class, required = false)
protected JAXBElement<String> productListDate;
@XmlElement(name = "Failed")
protected boolean failed;
@XmlElement(name = "FailedDescription", required = true, nillable = true)
protected String failedDescription;
...
}
我需要转换为GetProductListResponse
对象的XML示例存储在products.xml
文件中,它看起来像这样:
<GetProductListResult xmlns="http://productService.productsdata">
<ProductList>
<ProductListDetail>
<ProductName>SomeProductName</ProductName>
<ProductCost>9,45</ProductCost>
</ProductListDetail>
<ProductListDate>09.09.2015</ProductListDate>
<Failed>false</Failed>
<FailedDescription/>
</ProductList>
</GetProductListResult>
在convertXmlProductsTest
方法内部设置了转化调用 - 为此目的使用jaxb unmarshaller
:
public class ProductHandler {
public static GetProductListResponse convertXmlProductsTest(){
try {
JAXBContext jaxbContext = JAXBContext.newInstance(GetProductListResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
GetProductListResponse retval = (GetProductListResponse) jaxbUnmarshaller.unmarshal(new File("products.xml"));
return retval;
} catch (JAXBException ex) {
Logger.getLogger(ProductMockWs.class.getName()).log(Level.SEVERE, null, ex);
}
throw new UnsupportedOperationException("XML to Java object conversion failed.");
}
}
的问题是,产生的JAXB类GetProductListResponse
不包含@XmlRootElement
注解,所以这种转换失败与著名错误消息javax.xml.bind.UnmarshalException: unexpected element ... Expected elements are ...
。
当我手动将@XmlRootElement
注释添加到GetProductListResponse
类时,将其设置为:
@XmlRootElement(name="GetProductsListResult")
public class GetProductListResponse { ...}
转换成功。
问题:
有没有办法从该类外部为生成的类(@XmlRootElement
)设置GetProductListResponse
?
我想避免自定义生成的类,我不想更改WSDL定义。另外我读到了关于设置运行时注释的内容,但我想避免使用任何Java字节码操纵器(如Javassist)。
答案 0 :(得分:3)
JAXBContext jaxbContext = JAXBContext.newInstance(GetProductListResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<GetProductListResponse> root = jaxbUnmarshaller.unmarshal(new StreamSource(
file), GetProductListResponse.class);
GetProductListResponse productListResponse = root.getValue();
对于缺少的@XmlRootElement,这篇文章给了我很多帮助。看看:
http://www.source4code.info/2013/07/jaxb-marshal-unmarshal-with-missing.html
你可以在这里找到你的错误,看看你能做些什么!希望能帮助到你 !
答案 1 :(得分:0)
这可以在Jackson json/xml parser library中进行。杰克逊fully supports JAXB annotations及其mixin feature允许您从外部向外部添加注释。