【发布时间】:2016-04-16 11:16:18
【问题描述】:
我已经从 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 ...。
当我手动在GetProductListResponse类中添加@XmlRootElement注解,并将其设置为:
@XmlRootElement(name="GetProductsListResult")
public class GetProductListResponse { ...}
转换成功。
问题:
有没有办法从该类外部为生成的类(GetProductListResponse)设置@XmlRootElement?
我想避免自定义生成的类并且我不想更改 WSDL 定义。我还阅读了有关设置运行时注释的信息,但我想避免使用任何 Java 字节码操纵器(如 Javassist)。
【问题讨论】: