当我试图对XML文件进行解组时,我得到了null值,我已经创建了package-info.java类,其中有2个名称空间,如下所述。请建议如何解决这个问题
1.我的XML文件如下:它有两个名称空间
<?xml version="1.0" encoding="UTF-8"?>
<saleResponse xmlns="http://tripos.vantiv.com/2014/09/TriPos.Api" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<_type>saleResponse</_type>
</saleResponse>
2.我已经声明了package-info.java,如下所示
@XmlSchema(
elementFormDefault=XmlNsForm.QUALIFIED,
xmlns={
@XmlNs(prefix="", namespaceURI="http://tripos.vantiv.com/2014/09/TriPos.Api"),
@XmlNs(prefix="i", namespaceURI="http://www.w3.org/2001/XMLSchema-instance")
}
)
@XmlAccessorType(XmlAccessType.FIELD)
package test1;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.*;
3.SaleResponse类为:
package test1;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "saleResponse", namespace = "http://tripos.vantiv.com/2014/09/TriPos.Api")
public class SaleResponse {
@XmlElement(name = "_type")
public String _type;
}
4.当我尝试解组XML文件时,得到的值为null
package test1;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JAXBExample {
public static void main(String[] args) {
try {
File file = new File("C:\Ravi\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(SaleResponse.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
SaleResponse saleResponse = (SaleResponse) jaxbUnmarshaller.unmarshal(file);
System.out.println(saleResponse._type);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
**I am getting null value when i try to unmarshal XML file ,
I have created package-info.java class with 2 name spaces as explained below.
Please suggest how to fix this issue**
您必须将默认的namespace="http://tripos.vantiv.com/2014/09/TriPos.Api"
属性添加到package-info.java
中,还可以删除空前缀:@XmlNs(prefix="", namespaceURI="http://tripos.vantiv.com/2014/09/TriPos.Api")
。
它应该如您所期望的那样工作,输出为:saleResponse
包信息.java
@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED, namespace="http://tripos.vantiv.com/2014/09/TriPos.Api", xmlns = {
@XmlNs(prefix = "i", namespaceURI = "http://www.w3.org/2001/XMLSchema-instance") })
@XmlAccessorType(XmlAccessType.FIELD)
package test1;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
import javax.xml.bind.annotation.*;
有关详细信息:https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlSchema.html