How to deserialize Java objects from XML?

后端 未结 5 786
暗喜
暗喜 2021-01-16 08:01

I\'m sure this might have been discussed at length or answered before, however I need a bit more information on the best approach for my situation...

Problem

5条回答
  •  甜味超标
    2021-01-16 08:48

    You can use the @XmlPath extension in EclipseLink JAXB (MOXy) to easily handle this use case. For a detailed example see:

    • http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html

    Sample Code:

    package blog.geocode;
    
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    
    import org.eclipse.persistence.oxm.annotations.XmlPath;
    
    @XmlRootElement(name="kml")
    @XmlType(propOrder={"country", "state", "city", "street", "postalCode"})
    public class Address {
    
        @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:Thoroughfare/ns:ThoroughfareName/text()")
        private String street;
    
        @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:LocalityName/text()")
        private String city;
    
        @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:AdministrativeAreaName/text()")
        private String state;
    
        @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:CountryNameCode/text()")
        private String country;
    
        @XmlPath("Response/Placemark/ns:AddressDetails/ns:Country/ns:AdministrativeArea/ns:SubAdministrativeArea/ns:Locality/ns:PostalCode/ns:PostalCodeNumber/text()")
        private String postalCode;
    
    }
    

提交回复
热议问题