开发者

XML to Java Object

I am trying to convert an XML file to a Java Object, now, I have read of JAXB, XStream, Sax and DOM, I'd like to convert this sort of type of xml:

<testxml testtype="converting" duration="100.00" status="successful" />

it might be as well as:

<testxml testype="converting" duration="100.00"> successful </textxml>

I want开发者_Go百科ed to know if there is anything out there (and possibly not 3rd party) that I can use, without declaring a template in DTD or in JAXB in XSD but Java (therefore I will declare a java class called testxml with all the relevant variable i.e. testtype, duration, status>

Thank you all for your time.


The class below using JAXB Annotations will do exactly what you need, no need to create an XSD or a template using Java 1.6+:

@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());
  }
}

Using this as test.xml:

<testxml testtype="converting" duration="100.00"> successful </testxml>


You can do this pretty simply by using java.xml.bind.annotations on a Java class and JAXB.Unmarshal

JAXB is part of the JRE in java 1.6+


Try XStream/XPP3. That's good stuff. Takes a couple of hours to figure out. Does all the magic for you.


Personally I use XStream @ http://x-stream.github.io/ It's really easy to use and still offers enough features in case you need them. Unfortunately it looks like the project is not actively maintained anymore, but I haven't seen an alternative so far that suits my needs as well. I'd say it's worth spending a bit of time to check it out ;-)

edit: when you can use Java 6, I completely agree the other answers are preferable!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜