我有一个 String ,它将XML数据作为String。我想将此数据分配给 XMLNode 对象。你能建议我怎么做。
String xmlData = "<?xml version="1.0" encoding="UTF-8"?> <EMPDETAILSREPORTVO> <P_PERSON_ID>11</P_PERSON_ID> <LIST_EMPDETAILSREPORTVOROW> <EMPDETAILSREPORTVOROW> <EENAME>Camille Heiden</EENAME> <EMPLOYEENUMBER>10</EMPLOYEENUMBER> <JOBNAME>CON600.Consultant</JOBNAME> <SUPNAME>Sharon Colby</SUPNAME> <PROPOSEDSALARYN>3617.98</PROPOSEDSALARYN> <DATEPRINTED>2013-10-29T11:53:02.000+03:00</DATEPRINTED> </EMPDETAILSREPORTVOROW> </LIST_EMPDETAILSREPORTVOROW> </EMPDETAILSREPORTVO>";
XMLNode xmlNode = ???
希望将字符串设置为XMLNode对象
BM
答案 0 :(得分:0)
您可以使用JAXB执行此任务,请查看以下示例
//EMPDETAILSREPORTVO POJO
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "EMPDETAILSREPORTVO")
class EMPDETAILSREPORTVO{
private int P_PERSON_ID;
@XmlElement(name = "LIST_EMPDETAILSREPORTVOROW", type = LIST_EMPDETAILSREPORTVOROW.class)
List<LIST_EMPDETAILSREPORTVOROW> list = new ArrayList<LIST_EMPDETAILSREPORTVOROW>();
public EMPDETAILSREPORTVO() {
}
public EMPDETAILSREPORTVO(List<EMPDETAILSREPORTVOROW> list) {
this.list = list;
}
public void setEMPDETAILSREPORTVOList(List<EMPDETAILSREPORTVO> eList){
this.list = eList;
}
//other getters and setters ...
}
//EMPDETAILSREPORTVOROW POJO
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "EMPDETAILSREPORTVOROW")
class EMPDETAILSREPORTVOROW{
private String EENAME;
private int EMPLOYEENUMBER;
private String JOBNAME;
private String SUPNAME;
private double PROPOSEDSALARYN;
private Date DATEPRINTED;
//getters and setters...
}
public static void main(String [] args){
EMPDETAILSREPORTVOROW obj_1 = new EMPDETAILSREPORTVOROW();
obj_1.setEENAME("Name");
obj_1.setEMPLOYEENUMBER(110);
obj_1.setJOBNAME("Job Name");
obj_1.setSUPNAME("Supervisor Name");
obj_1.setPROPOSEDSALARYN(5000.00);
obj_1.setDATEPRINTED(new Date());
List<EMPDETAILSREPORTVOROW> list = new ArrayList<EMPDETAILSREPORTVOROW>();
list.add(obj_1);
EMPDETAILSREPORTVO eMPDETAILSREPORTVO = new EMPDETAILSREPORTVO(list);
eMPDETAILSREPORTVO.setEMPDETAILSREPORTVOList(list);
eMPDETAILSREPORTVO.setP_PERSON_ID(10);
marshalUser(eMPDETAILSREPORTVO);
}
//test
public static void marshal(EMPDETAILSREPORTVO object)
throws IOException, JAXBException {
JAXBContext context;
StringWriter stringWriter = new StringWriter();
context = JAXBContext.newInstance(Object.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.marshal(object, stringWriter);
System.out.println(stringWriter.toString());
stringWriter.close();
}
public static void unMarshal(String xmlString)
throws IOException, JAXBException {
try {
JAXBContext context = JAXBContext.newInstance(EMPDETAILSREPORTVO.class);
Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
StringReader reader = new StringReader(xmlString);
EMPDETAILSREPORTVO eMPDETAILSREPORTVO = (EMPDETAILSREPORTVO) jaxbUnmarshaller.unmarshal(reader);
} catch (Exception e) {
e.printStackTrace();
}
}