JAXB入门学习(三)
一个使用JAXB操作xml文档的小例子:
使用附件javaee-5-doc-tutorial-1.0_05.zip解压后 javaeetutorial5/examples/jaxb/modify-marshal所示例子,自己将其转变为Eclipse工程。在这里使用jdk1.5 jwsdp2.0 ant1.6,在project里不要忘记引入JAXB的jar包。
ant文件:
<?xml version="1.0" standalone="yes"?><project basedir="." default="compile"><!-- 设置jwsdp主目录 --> <property name="jwsdp.home" value="D:\Java\Sun\jwsdp-2.0" /><property name="classes.home" value="target/classes" /><property name="generate.code.home" value="src/primer" /> <path id="classpath"> <pathelement path="src" /> <pathelement path="${classes.home}" /> <!--for use with bundled ant--> <fileset dir="${jwsdp.home}" includes="jaxb/lib/*.jar" /> <fileset dir="${jwsdp.home}" includes="sjsxp/lib/*.jar" /> <fileset dir="${jwsdp.home}" includes="jwsdp-shared/lib/activation.jar" /> <fileset dir="${jwsdp.home}" includes="jwsdp-shared/lib/resolver.jar" /> </path><!-- 定义xjc任务 --> <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask"> <classpath refid="classpath" /> </taskdef> <target name="generate-code" > <echo message="Compiling the schema..." /><!-- 使用xjc任务根据xsd文件生成Java代码 --> <xjc schema="po.xsd" package="primer.po" destdir="src"> <produces dir="src/primer.po" includes="**/*.java" /> </xjc> </target> <!--compile Java source files--> <target name="compile" depends="generate-code" description="Compile all Java source files"> <echo message="Compiling the java source files..." /> <mkdir dir="${classes.home}"/> <javac destdir="${classes.home}" debug="on"> <src path="src" /> <classpath refid="classpath" /> </javac> </target> <target name="clean" description="删除生成的class文件及由xsd生成的Java代码"> <delete dir="${classes.home}" /> <delete deleteonexit="true" dir="${generate.code.home}" /> </target></project>
?
运行ant文件后(运行默认任务即可),运行Main类,可在控制台打印修改原xml文档后的内容,并可在project目录下生成一个newpo.xml文件:
package modifymarshal;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.math.BigDecimal;import java.math.BigInteger;import java.util.Date;import java.util.GregorianCalendar;import java.util.List;import java.util.Locale;import java.util.TimeZone;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBElement;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import javax.xml.datatype.Duration;import javax.xml.datatype.XMLGregorianCalendar;import javax.xml.namespace.QName;import com.sun.org.apache.bcel.internal.generic.GETSTATIC;import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;// import java content classes generated by binding compilerimport primer.po.*;import primer.po.Items.Item;/** * * @author liu_yming * */public class Main { // This sample application demonstrates how to modify a java content // tree and marshal it back to a xml data public static void main(String[] args) { try { // 创建一个 JAXBContext 的实例处理生成的primer.po包底下的类 JAXBContext jc = JAXBContext.newInstance("primer.po"); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); // 已经废弃的setValidating方法 // u.setValidating(true); // 读取xml文档并unmarshal(xml2java 解组)至content tree JAXBElement poe = (JAXBElement) u.unmarshal( new FileInputStream("po.xml")); PurchaseOrderType po = (PurchaseOrderType) poe.getValue(); // 输出po.xml文档中的内容 USAddress shipTo = po.getShipTo(); System.out.println("shipTo name: " + shipTo.getName()); System.out.println("shipto country: " + shipTo.getCountry()); System.out.println("**********************************"); USAddress billTo = po.getBillTo(); System.out.println("billTo name: " + billTo.getName()); System.out.println("billTo country: " + billTo.getCountry()); System.out.println("**********************************"); Items items = po.getItems(); List<Item> itemList = items.getItem(); for (Item item:itemList) { System.out.println("item attribute partNum : " + item.getPartNum()); System.out.println("item element comment : " + item.getComment()); System.out.println("item element ProductName : " + item.getProductName()); System.out.println("item element Quantity : " + item.getQuantity()); System.out.println("item element ShipDate : " + item.getShipDate()); System.out.println("-----------------------------"); } System.out.println("**********************************"); // change the billto address USAddress newBillTo = po.getBillTo(); newBillTo.setCountry("CN"); newBillTo.setName("Kevin Liu"); newBillTo.setStreet("XueYuan road 388"); newBillTo.setCity("KunShan"); newBillTo.setState("JiangSu"); newBillTo.setZip(new BigDecimal("258311")); // change the first item Item newItem = itemList.get(0); newItem.setPartNum("444-CN"); newItem.setComment("水泥杀手"); newItem.setProductName("安踏"); newItem.setShipDate(XMLGregorianCalendarImpl.parse("20100603")); newItem.setQuantity(BigInteger.valueOf(3)); // 创建一个Marshaller 并marshal(编组 java2xml)只newpo.xml文件并在控制台打印输出 Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // 输出的控制台 m.marshal(poe, System.out); // 输出到新的文件 //m.marshal(poe, new FileOutputStream(new File("newpo.xml"))); } catch (JAXBException je) { je.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }}
?