0

I want to create constructor which takes xml as string and all variables would be fill from that. That xml is created by XStream so I think that something like this would work but don´t know what to add to left side:

    public xmlpacket(String xml)
    {
        XStream xstream = new XStream(new DomDriver());
       .... =  (xmlpacket)xstream.fromXML(xml);
    }

Thank you

Libor Zapletal
  • 13,752
  • 20
  • 95
  • 182

3 Answers3

1

You can make use of a static method.

public static XMLPacket unmarshall(String xml) {
    XStream xstream = new XStream(new DomDriver());

    return (XMLPacket)xstream.fromXML(xml);

}

Notice how I renamed your class. Now it adheres to Java Naming Conventions.

adarshr
  • 61,315
  • 23
  • 138
  • 167
1

If you've created the classes you need and the xstream aliases for the classes then

XMLPacket packet = (XMLPacket)xstream.fromXML(xml);

But you should probably create a method for this and not do it in the constructor.

ChadNC
  • 2,528
  • 4
  • 25
  • 39
0

XStream will create the instance of the object for you. So unless you want to copy all the attributes of the XStream-created packet to the packet you're constructing, it makes no sense to do that in a constructor. Create a factory method instead:

public static XmlPacket fromXml(String xml) {
    XStream xstream = new XStream(new DomDriver());
    return (XmlPacket) xstream.fromXML(xml);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255