Deserialization of xml with simplexml in java

前端 未结 2 1794
花落未央
花落未央 2021-01-19 12:29

I\'m trying to deserialize an xml string with SimpleXML, i\'ve looked at their examples but i\'m not really sure that wether i grasp the concept or not.

Sample XML (

相关标签:
2条回答
  • 2021-01-19 12:49

    I have a suggestion, but it's not ready to run (see below). However, ther maybe another, better solution ...

    Class Item

    Holding all your informations.

    @Root(name="Item")
    public class Item
    {
        @Element(name="ID", required=true)
        private int id;
        @Element(name="language", required=true)
        private String language;
        @Element(name="price", required=true)
        private int price;
    
    
        // ...
    }
    

    Class Result

    Constructing everything around Item. Btw. you dont have to use inner classes here.

    @Namespace(prefix="soap", reference="http://schemas.xmlsoap.org/soap/envelope/")
    @Root(name="Envelope")
    public class Result
    {
        @Namespace(prefix="soap")
        @Element(name="Body")
        private SoapBody body;
    
    
        // ...
    
    
        // -----------------------------------------------------------------
        // -- Some inner classes, constructing the elements as in you xml --
        // -----------------------------------------------------------------
    
    
        @Namespace(prefix="soap")
        @Root(name="Body")
        static class SoapBody
        {
            @Element(name="Response")
            private Response response;
    
    
            // ...
        }
    
    
    
        @Root(name="Response")
        static class Response
        {
            @ElementList(name="Result", required=true)
            private List<Item> result;
    
    
            // ...
        }
    }
    

    (Example) How to use this code

    Writing

    File f = ...
    
    Serializer ser = new Persister();
    Result r = new Result();
    ser.write(r, f);
    

    Reading

    File f = ...
    
    Serializer ser = new Persister();
    Result r = ser.read(Result.class, f);
    

    Now ... there's one problem which prevents this example from running: <language /> This empty Element let SimpleXML throw a ValueRequiredException.

    0 讨论(0)
  • 2021-01-19 13:09
     @Element( required=false)
        private String language;
    

    Add this in your Item class and generate the getter and setter.I think it should work

    0 讨论(0)
提交回复
热议问题