我正在尝试将XML文件转换为Java对象,现在,我已经阅读了JAXB,XStream,Sax和DOM,我想转换这种类型的xml:
<testxml testtype="converting" duration="100.00" status="successful" />
Run Code Online (Sandbox Code Playgroud)
它可能会:
<testxml testype="converting" duration="100.00"> successful </textxml>
Run Code Online (Sandbox Code Playgroud)
我想知道是否有任何东西(可能不是第三方)我可以使用,而不是在DTD或XSD中的JAXB中声明模板而是Java(因此我将声明一个名为testxml的java类,其中包含所有相关变量即testtype,duration,status>
谢谢大家的时间.
小智 11
使用JAXB Annotations的下面的类将完全满足您的需求,无需使用Java 1.6+创建XSD或模板:
@XmlRootElement
public class TestXML {
private String testtype;
private double duration;
private String status;
public void setTesttype(String testtype) {
this.testtype = testtype;
}
@XmlAttribute
public String getTesttype() {
return testtype;
}
public void setDuration(double duration) {
this.duration = duration;
}
@XmlAttribute
public double getDuration() {
return duration;
}
public void setStatus(String status) {
this.status = status;
}
@XmlValue
public String getStatus() {
return status;
}
public static void main(String args[]) {
TestXML test = JAXB.unmarshal(new File("test.xml"), TestXML.class);
System.out.println("testtype = " + test.getTesttype());
System.out.println("duration = " + test.getDuration());
System.out.println("status = " + test.getStatus());
}
}
Run Code Online (Sandbox Code Playgroud)
用它作为test.xml:
<testxml testtype="converting" duration="100.00"> successful </testxml>
Run Code Online (Sandbox Code Playgroud)