标准化的JAXB实现Java Bean与 XML的绑定
XML example:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <wwprttxn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <price xsi:type="referencePriceElementType" type="I"> <offering>6948</offering> <startdate>2011-04-21</startdate> <currency>EUR</currency> <cabletype>ANN</cabletype> <cableid>N2Z11M026589</cableid> <releasets>2011-04-21T19:51:17.649</releasets> <pricevalue>0.000000</pricevalue> <pricepointtype>FEA</pricepointtype> <pricepointvalue>5076</pricepointvalue> <country>AT</country> <pricetype>XAC</pricetype> <onshore>true</onshore> <enddate>9999-12-31</enddate> <pricevalueusd>0.000000</pricevalueusd> <factor>1.000000</factor> </price> </wwprttxn>
P.S.
1. xs:dateTime
xs:dateTime是schema定义的日期时间型,当使用xs:dateTime()来强制转换某个字符串为日期时间型时,字符串的格式应该是:yyyy-mm-ddTHH:MM:SS
例如:2007-03-11T11:09:05,
其中的"T"为日期和时间的分割符,是必须的.
关键的步骤是定义一个合法的XML Schema:
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:this="http:///TestXML/Jaxb_test_1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="wwprttxn"> <xs:complexType> <xs:sequence> <xs:element name="price" maxOccurs="unbounded" type="PriceType"> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="PriceType"> <xs:sequence> <xs:element name="offering" type="xs:string"/> <xs:element name="startdate" type="xs:date"/> <xs:element name="currency" type="xs:string"/> <xs:element name="cabletype" type="xs:string"/> <xs:element name="cableid" type="xs:string"/> <xs:element name="releasets" type="xs:dateTime"/> <xs:element name="pricevalue" type="xs:string"/> <xs:element name="pricepointtype" type="xs:string"/> <xs:element name="pricepointvalue" type="xs:string"/> <xs:element name="country" type="xs:string"/> <xs:element name="pricetype" type="xs:string"/> <xs:element name="onshore" type="xs:string"/> <xs:element name="enddate" type="xs:string"/> <xs:element name="pricevalueusd" type="xs:string"/> <xs:element name="factor" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:schema>
由这个XSD文件生成需要的JAVA Bean Skeleton:
最后就可以使用JAXB的标准方法将XML解析成Java Bean:
/*
* The String Parameter is the package name which contains the ObjectFactory
*/
JAXBContext jc = JAXBContext.newInstance("test.xml");
Unmarshaller u = jc.createUnmarshaller();
Wwprttxn w = (Wwprttxn)u.unmarshal(new File("D:/test/53.msg"));
List<PriceType> priceList= w.getPrice();
P.S.
1. JAXB2.0 里Validator类已经Deprecated.
2. JAXBContext.newInstance(String packageName), PackageName里需要包含上图中的ObjectFactory.