자바 object 와 xml 사이 의 변환

그 동안 o/x mapping,즉 자바 object 와 xml 간 의 전환 과 xml 파일 검증 문 제 를 연구 하면 서 자신 도 작은 프 리 젠 테 이 션 예 를 개발 했다.다음 과 같다.
개발 환경
1.jdk1.5
2.jwsdp 2.0(Java Web Services Developer Pack 2.0,sun 홈 페이지 에 있 는 아래)
3.프로그램 에 필요 한 jar 패키지:
%jwsdp 2.0 설치 디 렉 터 리 아래%/jaxb/lib/jaxb-api.jar
%jwsdp 2.0 설치 디 렉 터 리 아래%/jaxb/lib/jaxb-impl.jar
%jwsdp 2.0 설치 디 렉 터 리 아래%/sjsxp/lib/jsr 173api.jar
%jwsdp 2.0 설치 디 렉 터 리 아래%/jwsdp-shared/lib/activation.jar
4.개발 도구:eclipse 3.2
---------------------
XML schema 파일--library.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="librarys" type="librarys"/>
<xs:complexType name="librarys">
	<xs:sequence>
		<xs:element name="library" minOccurs="1" maxOccurs="unbounded">
			<xs:complexType>
				<xs:sequence>
					<xs:element name="name" type="xs:string"/>
					<xs:element name="layer" type="xs:int"/>
					<xs:element name="row" type="xs:int"/>
					<xs:element name="book" type="book"/>
				</xs:sequence>
			</xs:complexType>
		</xs:element>
	</xs:sequence>
</xs:complexType>
<xs:complexType name="book">
	<xs:sequence>
		<xs:element name="bookID" type="xs:string"/>
		<xs:element name="bookName" type="xs:string"/>
		<xs:element name="borrowDate" type="xs:date"/>
		<xs:element name="user" type="user"/>
	</xs:sequence>
	<xs:attribute name="description" type="xs:string"/>
</xs:complexType>
<xs:complexType name="user">
	<xs:sequence>
		<xs:element name="userID" type="xs:string"/>
		<xs:element name="userName" type="xs:string"/>
		<xs:element name="userAge" type="xs:int"/>
	</xs:sequence>
</xs:complexType>
</xs:schema>

jwsdp 의 xjc 도 구 를 정의 하 는 binding 파일---binding.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="library.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.cuishen.o_x_mapping.object"/>
        <!--       JAVA        -->
        <jxb:nameXmlTransform>
	    		 <jxb:elementName suffix="Element"/>
				</jxb:nameXmlTransform>
    </jxb:schemaBindings>
    <!--      xsd        Java    (        ,       ) -->
    <jxb:bindings node="//xs:complexType[@name='librarys']">
        <jxb:class name="Librarys"/>
    </jxb:bindings>
    <jxb:bindings node="//xs:complexType[@name='book']">
        <jxb:class name="Book"/>
        <!--                  Java       (        ,       ) -->
        <jxb:bindings node=".//xs:element[@name='bookID']">
            <jxb:property name="id"/>
        </jxb:bindings>
    </jxb:bindings>
    <jxb:bindings node="//xs:complexType[@name='user']">
        <jxb:class name="User"/>
        <!--                  Java       (        ,       ) -->
        <jxb:bindings node=".//xs:element[@name='userID']">
            <jxb:property name="id"/>
        </jxb:bindings>
    </jxb:bindings>
  </jxb:bindings>
</jxb:bindings>

주의!binding 파일 의 인 코딩 형식 은 UTF-8 을 사용 해 야 합 니 다.코드 를 eclipse 에 직접 붙 이면 인 코딩 형식 이 UTF-8 이 아 닙 니 다.이때 xjc 도구 가 잘못 보고 되 었 습 니 다.해결 방법 은 이 파일 을 UltraEdit 도구 로 바 꾸 는 것 입 니 다.
binding 파일 과 xsd 파일 을 통 해 jaxb 자체 xjc 도구 로 자바 object 를 자동 으로 생 성 할 수 있 습 니 다.좋 지 않 습 니까^ ^
현재 o/x mapping 의 테스트 주 클래스-main.자바

package com.cuishen.o_x_mapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.GregorianCalendar;
import java.util.List;

import javax.xml.XMLConstants;
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.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.ValidationEventLocator;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import com.cuishen.o_x_mapping.object.Book;
import com.cuishen.o_x_mapping.object.Librarys;
import com.cuishen.o_x_mapping.object.User;
import com.cuishen.o_x_mapping.object.ObjectFactory;

import com.cuishen.o_x_mapping.utils.FileUtils;;

/**
 * o/x mapping    
 * @author cuishen
 * @date 2008-4-2
 * @version 1.0
 */
public class Main {
	public static void object2xml() {
		try {
			JAXBContext context = JAXBContext.newInstance("com.cuishen.o_x_mapping.object");
			
			Librarys libs = new Librarys();
			List<Librarys.Library> libList = libs.getLibrary();
			
			User usr = createUser("1011", 28, "cuishen");
			Book book = createBook("        ", getDate(), "     ", "88-91-211", usr);			
			libList.add(createLibrary("     ", 2, 4, book));
			
			usr = createUser("1017", 22, "sanmao");
			book = createBook("   ", getDate(), "  ", "34-16-310", usr);			
			libList.add(createLibrary("     ", 3, 11, book));
			
			// create an element for marshalling
			JAXBElement<Librarys> element = (new ObjectFactory()).createLibrarys(libs);
			
			Marshaller m = context.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			m.setProperty("jaxb.encoding", "gbk");
			m.marshal(element, System.out);
			File xmlFile = FileUtils.makeFile(getXmPath());
			OutputStream ot = new FileOutputStream(xmlFile);
			m.marshal(element, ot);
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void xml2object(Unmarshaller u) {
		try {
			//JAXBContext jc = JAXBContext.newInstance( "com.cuishen.o_x_mapping.object" );
			
			//Unmarshaller u = jc.createUnmarshaller();
			
			// unmarshal a po instance document into a tree of Java content
			// objects composed of classes from the com.cuishen.o_x_mapping.object package.
			JAXBElement poe = (JAXBElement)u.unmarshal(new FileInputStream(getXmPath()));
			Librarys librarys = (Librarys)poe.getValue();
			
			List libList = librarys.getLibrary();
			for(int i = 0; i < libList.size(); i++) {
				Librarys.Library lib = (Librarys.Library)libList.get(i);
				System.out.println("librarys ==> ");
				System.out.println("===> library :");
				System.out.println("=========> layer " + lib.getLayer());
				System.out.println("=========> name " + lib.getName());
				System.out.println("=========> row " + lib.getRow());
				System.out.println("=========> book :");
				Book book = lib.getBook();
				System.out.println("=============> id " + book.getId());
				System.out.println("=============> borrowDate " + book.getBorrowDate());
				System.out.println("=============> name " + book.getBookName());
				System.out.println("=============> desc " + book.getDescription());
				System.out.println("=============> user :");
				User usr = book.getUser();
				System.out.println("==================> userID " + usr.getId());
				System.out.println("==================> userName " + usr.getUserName());
				System.out.println("==================> Age " + usr.getUserAge());            	
			}
			
		} catch( JAXBException je ) {
			je.printStackTrace();
		} catch( IOException ioe ) {
			ioe.printStackTrace();
		}
	}
	
	/**
	 *  xml        
	 * @return boolean
	 */
	public static Unmarshaller validate() {
		// create a JAXBContext capable of handling classes generated into
		// the com.cuishen.o_x_mapping.object package
		JAXBContext jc;
		Unmarshaller u = null;
		try {
			jc = JAXBContext.newInstance( "com.cuishen.o_x_mapping.object" );
			
			u = jc.createUnmarshaller();
			
			SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			try {
				Schema schema = sf.newSchema(new File(getXSDPath()));
				u.setSchema(schema);
				u.setEventHandler(
						new ValidationEventHandler() {
							public boolean handleEvent(ValidationEvent ve) {
								if (ve.getSeverity() == ValidationEvent.WARNING || ve.getSeverity() != ValidationEvent.WARNING) {
									ValidationEventLocator vel = ve.getLocator();
									System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage());
									return false;
								}
								return true;
							}
						}
				);
			} catch (org.xml.sax.SAXException se) {
				System.out.println("Unable to validate due to following error.");
				se.printStackTrace();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return u;
	}
	
	private static String getXmPath() throws MalformedURLException {
		String xmlPath = FileUtils.extractDirPath(FileUtils.extractDirPath(Main.class.getClassLoader().getResource(".").toString()));
		xmlPath = FileUtils.makeFilePath(xmlPath, "src/com/cuishen/o_x_mapping/xml/library.xml");
		URL url = new URL(xmlPath);
		return url.getPath();
	}
	
	private static String getXSDPath() throws MalformedURLException {
		String xsdPath = FileUtils.extractDirPath(FileUtils.extractDirPath(Main.class.getClassLoader().getResource(".").toString()));
		xsdPath = FileUtils.makeFilePath(xsdPath, "library.xsd");
		URL url = new URL(xsdPath);
		System.out.println("xsd path ==========> " + url.getPath());
		return url.getPath();		
	}
	
	public static void main(String args[]) {		
		System.out.println("======== object to xml ...");
		object2xml();
		System.out.println("======== xml to object ...");
		xml2object(validate());
	}
	public static Librarys.Library createLibrary(String name, int layer, int row, Book book) {
		Librarys.Library library = new Librarys.Library();
		library.setName(name);
		library.setLayer(layer);
		library.setRow(row);
		library.setBook(book);
		return library;
	}
	public static Book createBook(String name, XMLGregorianCalendar date, String desc, String id, User usr) {
		Book book = new Book();
		book.setBookName(name);
		book.setBorrowDate(date);
		book.setDescription(desc);
		book.setId(id);
		book.setUser(usr);
		return book;
	}
	public static User createUser(String id, int age, String name) {
		User usr = new User();
		usr.setId(id);
		usr.setUserAge(age);
		usr.setUserName(name);
		return usr;
	}
	private static XMLGregorianCalendar getDate() {
		try {
			return DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
		} catch (DatatypeConfigurationException e) {
			throw new Error(e);
		}
	}
}

상기 코드 의 핵심 은 xml 파일 의 컴 파일 화해 그룹 입 니 다.인터페이스 javax.xml.bid.Marshaller(Marshaller 류 는 자바 콘 텐 츠 트 리 를 XML 데이터 로 직렬 화 하 는 과정 을 관리 합 니 다.기본 적 인 컴 파일 방법 marshal)과 인터페이스 javax.xml.bid.Unmarshaller(Unmarshaller 류 관리 가 XML 데 이 터 를 새로 만 든 자바 콘 텐 츠 트 리 로 반 직렬 화 하 는 과정 을 제공 합 니 다.그룹 을 풀 때 XML 데 이 터 를 선택적으로 검증 할 수 있 습 니 다.다양한 입력 종류 에 따라 여러 가지 무 거 운 unmarshal 방법 을 제공 합 니 다.)xml 파일 에 대한 검증 은 그룹 을 풀 때 호출 방법 인 unmarshal 이 인증 을 촉발 하 는 메커니즘 으로 xml 파일 이 schema 의 규범 에 부합 되 는 지 검증 합 니 다.
다음은 build.xml 를 정의 합 니 다.ant 도구 로 전체 프로젝트 의 컴 파일 과 실행 을 완성 합 니 다.편리 하고 빠 릅 니 다.^ ^

<project basedir="." default="run">
  <!--   jwsdp      -->
  <property name="jwsdp.home" value="d:\Sun\jwsdp-2.0"/>
  <!--   log4j      -->
  <property name="log4j.home" value="D:\conserv\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="library.xsd" binding="binding.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.cuishen.o_x_mapping.Main" fork="true">
      <classpath refid="xjc.classpath" />
    </java>
  </target>
  
</project>

저 는 이미 프레젠테이션 프로젝트 의 전체 코드 를 첨부 파일 에 포장 하여 올 렸 습 니 다.테스트 를 통과 하여 네티즌 들 이 다운로드 하 는 데 편리 하고 부족 한 점 이 있 으 면 여러분 과 토론 하고 싶 습 니 다.

좋은 웹페이지 즐겨찾기