我尝试使用 JAXB 将 XML 转换为 Java,但未按预期工作。围绕它还有多个其他类似的问题,但我研究的建议解决方案似乎都对我没有帮助。
下面是我的 bean
@XmlRootElement(name = "ListingResponse", namespace = "http://www.random.com")
@XmlType(propOrder = {"success", "listingId", "description"})
public class ListingResponse {
private String success;
private String listingId;
private String description;
public String getSuccess() {
return success;
}
@XmlElement(name = "Success")
public void setSuccess(String success) {
this.success = success;
}
public String getListingId() {
return listingId;
}
@XmlElement(name = "ListingId")
public void setListingId(String listingId) {
this.listingId = listingId;
}
public String getDescription() {
return description;
}
@XmlElement(name = "Description")
public void setDescription(String description) {
this.description = description;
}
下面是我尝试进行解码
ListingResponse response = null;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(ListingResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
response = (ListingResponse) jaxbUnmarshaller.unmarshal(new File("response.xml"));
} catch (JAXBException e) {
e.printStackTrace();
}
最后是我的response.xml内容
<ListingResponse xmlns="http://www.random.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Success>true</Success>
<Description>ListingId 123 created.</Description>
<ListingId>123</ListingId>
</ListingResponse>
- 没有抛出异常。
- “响应”不为空。
- 我尝试添加
@XmlAccessorType(XmlAccessType.FIELD/PROPERTY)
在 fields/set 方法上使用@XMLEelement
注释,但这似乎也没有帮助。
但是,响应始终为“空”,没有初始化任何字段。
你们能发现这里的问题吗?
最佳答案
当前您仅为根元素指定了正确的命名空间限定。您需要使用包级别 @XmlSchema
注释来映射模型的命名空间限定。
package-info.java
@XmlSchema(
namespace = "http://www.random.com",
elementFormDefault = XmlNsForm.QUALIFIED)
package example;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
了解更多信息
关于java - XML 到 Java JaxB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913312/