JAXB 对象与xml映射

导入jaxb所需要的jar文件。注意如果你是jdk1.6的话,不要用jwsdp2.0,2.0支持jdk1.5.





首先定义xsd文件。

players.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
	elementFormDefault="qualified" attributeFormDefault="unqualified">
	<xs:element name="club" type="Club" />
	<xs:complexType name="Club">
		<xs:sequence>
			<xs:element name="name" type="xs:string" />
			<xs:element name="createdDate" type="xs:date" />
			<xs:element name="coach" type="xs:string" />
			<xs:element name="players" minOccurs="1" maxOccurs="unbounded">
				<xs:complexType>
					<xs:sequence>
						<xs:element name="name" type="xs:string" />
						<xs:element name="position" type="xs:string" />
						<xs:element name="country" type="xs:string" />
						<xs:element name="num" type="xs:string" />
						<xs:element name="description" type="xs:string" />
					</xs:sequence>
				</xs:complexType>
			</xs:element>

		</xs:sequence>
	</xs:complexType>


</xs:schema>

 定义xjb文件  playersbinding.xjb

<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <jxb:bindings schemaLocation="players.xsd" node="/xs:schema"><!-- schemaLocation属性是xsd文件的相对路径 -->
    <jxb:globalBindings 
	fixedAttributeAsConstantProperty="true" 
	collectionType="java.util.ArrayList" 
	typesafeEnumBase="xs:NCName" 
	choiceContentProperty="false" 
	typesafeEnumMemberName="generateError" 
	enableFailFastCheck="false" 
	generateIsSetMethod="false" 
	underscoreBinding="asCharInWord"/>
    <jxb:schemaBindings>
        <jxb:package name="com.zhuyang.mapping.object"/>
        <!-- 这里是生成的JAVA类文件存放包名 -->
        <jxb:nameXmlTransform>
	    		 <jxb:elementName suffix="Element"/>
				</jxb:nameXmlTransform>
    </jxb:schemaBindings>
    <!-- 这里是定义xsd中一个复合类型与Java类的映射(如果要修改才定义,不修改则不需要) -->
    <jxb:bindings node="//xs:complexType[@name='Club']">
        <jxb:class name="Club"/>
    </jxb:bindings>
   
   
  </jxb:bindings>
</jxb:bindings>

 最后ant脚本用来生成java对象

playersbuild.xml

<project basedir="." default="run">
	<!--这里是jwsdp的安装目录 -->
	<property name="jwsdp.home" value="C:\axis2\Sun\jwsdp-2.0" />
	<!--这里是log4j的安装目录 -->
	<property name="log4j.home" value="C:\axis2\o-x-mapping\o-x-mapping\implement\lib" />
	<path id="xjc.classpath">
		<pathelement path="src" />
		<pathelement path="bin" />
		<pathelement path="lib" />
		<pathelement path="schemas" />
		<!--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" />
		<fileset dir="${log4j.home}" includes="log4j-1.2.5.jar" />
	</path>
	<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
		<classpath refid="xjc.classpath" />
	</taskdef>

	<!--compile Java source files-->
	<target name="compile" description="Compile all Java source files">
		<echo message="Compiling the schema..." />
		<!-- mkdir dir="src" /-->
		<xjc schema="players.xsd" binding="playersbinding.xjb" destdir="src" />
		<echo message="Compiling the java source files..." />
		<mkdir dir="bin" />
		<javac destdir="bin" debug="on">
			<src path="src" />
			<classpath refid="xjc.classpath" />
		</javac>
	</target>

	<target name="run" depends="compile" description="Run the sample app">
		<echo message="Running the sample application..." />
		<java classname="com.zhuyang.mapping.object.Test" fork="true">
			<classpath refid="xjc.classpath" />
		</java>
	</target>

</project>

 

Test.java

package com.zhuyang.mapping.object;

import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class Test {

	/**
	 * @param args
	 * @throws JAXBException
	 */

	public static void object2xml() throws JAXBException {
		JAXBContext jaxbContent = JAXBContext
				.newInstance("com.zhuyang.mapping.object");
		Club.Players players1 = new Club.Players();
		players1.setCountry("巴西");
		players1.setName("罗纳尔多");
		players1.setNum("9");
		players1.setPosition("中锋");
		players1.setDescription("外星人");
		Club.Players players2 = new Club.Players();
		players2.setCountry("中国");
		players2.setName("李毅");
		players2.setNum("14");
		players2.setDescription("带球像亨利");
		players2.setPosition("中锋");
		Club.Players players3 = new Club.Players();
		players3.setCountry("英格兰");
		players3.setName("欧文");
		players3.setNum("10");
		players3.setDescription("金童");
		players3.setPosition("中锋");
		Club.Players players4 = new Club.Players();
		players4.setCountry("威尔士");
		players4.setName("贝尔");
		players4.setNum("3");
		players4.setPosition("右后卫");
		players4.setDescription("速度变态");
		
		 
		
		Club c = new Club();
		List<Club.Players> players=c.getPlayers();
		players.add(players1);
		players.add(players2);
		players.add(players3);
		players.add(players4);
		c.setCoach("Mario");
		c.setCreatedDate(getDate());
		c.players=players;
		c.setName("Real Madrid");
		JAXBElement<Club> element = (new ObjectFactory()).createClub(c);
		Marshaller marshaller = jaxbContent.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		marshaller.setProperty("jaxb.encoding", "utf-8");
		marshaller.marshal(element, System.out);

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			object2xml();
			System.out.println(System.getProperty("user.dir"));
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static XMLGregorianCalendar getDate() {
		try {
			return DatatypeFactory.newInstance().newXMLGregorianCalendar(
					new GregorianCalendar(2011,2,20) {
					});
		} catch (DatatypeConfigurationException e) {
			throw new Error(e);
		}
	}
}
 

 

你可能感兴趣的:(java,C++,c,log4j,xml)