如何將一個xml文件轉換爲簡單的java bean? 它是一個簡單的xml文件,沒有任何xsd,它是從我沒有訪問的java bean生成的。將xml轉換爲java bean
我嘗試使用xmlbeans首先從xml生成xmd,然後從xsd生成類。我有一堆課。我正在尋找一個單獨的java bean類。
如何將一個xml文件轉換爲簡單的java bean? 它是一個簡單的xml文件,沒有任何xsd,它是從我沒有訪問的java bean生成的。將xml轉換爲java bean
我嘗試使用xmlbeans首先從xml生成xmd,然後從xsd生成類。我有一堆課。我正在尋找一個單獨的java bean類。
您可以使用像Castor或JAXB這樣的工具將XML映射到java類。 Castor相當容易使用。
JAXB
JAXB(JSR-222)提供了一種簡單的方法將對象轉換爲XML。有此標準的許多開放源代碼實現,包括:(包含在Java SE 6的參考實現)
JAXB具有Java對象到XML的默認映射。該映射可以通過應用註釋來定製。
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.Element;
@XmlRootElement
public class Address {
private String street;
private String city;
private String state;
private String country;
@XmlElement(name="postal-code")
private String postalCode;
}
將對應於下面的XML:
<address>
<street>123 A Street</street>
<city>Any Town</city>
<state>A State</state>
<postal-code>12345</postal-code>
</address>
的EclipseLink JAXB(MOXY)
MOXY具有基於XPath映射擴展。這意味着我們可以把我們的同一個Address類,並將其映射到谷歌的地理編碼格式:
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;
}
上面的類對應於以下XML:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.0" xmlns:ns="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0">
<Response>
<Placemark>
<ns:AddressDetails>
<ns:Country>
<ns:CountryNameCode>US</ns:CountryNameCode>
<ns:AdministrativeArea>
<ns:AdministrativeAreaName>CA</ns:AdministrativeAreaName>
<ns:SubAdministrativeArea>
<ns:Locality>
<ns:LocalityName>Mountain View</ns:LocalityName>
<ns:Thoroughfare>
<ns:ThoroughfareName>1600 Amphitheatre Pkwy</ns:ThoroughfareName>
</ns:Thoroughfare>
<ns:PostalCode>
<ns:PostalCodeNumber>94043</ns:PostalCodeNumber>
</ns:PostalCode>
</ns:Locality>
</ns:SubAdministrativeArea>
</ns:AdministrativeArea>
</ns:Country>
</ns:AddressDetails>
</Placemark>
</Response>
</kml>
欲瞭解更多信息