小编典典
您可以使用此代码检索POJO,还可以将@XmlRootElement作为标头添加到POJO。
(我没有测试下面的代码)
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
xsr.nextTag(); // Advance to Envelope tag
xsr.nextTag(); // Advance to Body tag
xsr.nextTag();
xsr.nextTag();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StringWriter stringWriter = new StringWriter();
transformer.transform(new StAXSource(xsr), new StreamResult(stringWriter));
StringReader sr = new StringReader(stringWriter.toString());
JAXBContext jaxbContext = JAXBContext.newInstance(LoginResult.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
LoginResult loginResult = (LoginResult) unmarshaller.unmarshal(sr);
编辑:
我为您找到了解决方案:
@XmlRootElement(name = "LoginResult", namespace = "http://test.org/ADMail_Service")
@XmlAccessorType(XmlAccessType.FIELD)
public class LoginResult {
@XmlElement(name = "ErrorMessage", namespace = "http://test.org/ADMail_Service")
private String errorMessage;
@XmlElement(name = "Status", namespace = "http://test.org/ADMail_Service")
private String status;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
public static void main(String[] args) {
try {
XMLInputFactory xif = XMLInputFactory.newFactory();
XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
xsr.nextTag(); // Advance to Envelope tag
xsr.nextTag(); // Advance to Body tag
xsr.nextTag();
xsr.nextTag();
JAXBContext jc = JAXBContext.newInstance(LoginResult.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement je = unmarshaller.unmarshal(xsr, LoginResult.class);
System.out.println(je.getName());
System.out.println(je.getValue());
System.out.println(je.getValue().getErrorMessage());
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
2020-10-16