前面有介绍过json-lib这个框架,在线博文:
http://www.cnblogs.com/hoojo/archive/2011/04/21/2023805.html
以及Jackson这个框架,在线博文: http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
它们都可以完成Java对象到XML的转换,但是还不是那么的完善。还有XStream对JSON及XML的支持,它可以对JSON或XML的完美转换。在线博文:
http://www.cnblogs.com/hoojo/archive/2011/04/22/2025197.html
这里将介绍Castor来完成Java对象到xml的相互转换。它是怎么样转换的?和前面不同的是castor可以用一个mapping.xml文件来描述转换后的Java对象的xml基本形态,类似于xStream的annotation,这点还是非常不错的。下面我们就来看看Castor是怎么样完成Java对象到XML之间的相互转换吧。
原文地址
用Castor 处理XML文档
http://www.cnblogs.com/hoojo/archive/2011/04/25/2026819.html
以下是学习笔记:
1,改造成Maven工程后的pom.xml文件,这里要注意,castor-1.3.3.jar虽然可以在Maven仓库里面看到,但不能下载,我们需要的jar在床上castor-xml-1.3.3.jar里:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.coderdream</groupId> <artifactId>castor-demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>castor-demo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <plugin.compiler.version>3.1</plugin.compiler.version> <junit.version>4.11</junit.version> <log4j.version>1.2.12</log4j.version> <commons.io.version>1.3.2</commons.io.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.codehaus.castor</groupId> <artifactId>castor-xml-diff</artifactId> <version>1.3.3</version> </dependency> </dependencies> <build> <finalName>castor-demo</finalName> </build> </project>
2,完整的CastorTest.java文件:
package com.hoo.test; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.hoo.entity.Account; import com.hoo.entity.AccountArray; import com.hoo.entity.Birthday; import com.hoo.entity.ListBean; import com.hoo.entity.MapBean; /** * <b>function:</b>Castor完成Java对象到XML的相互转换 依赖jar: castor-1.3.jar castor-1.3-core.jar junit-4.8.2.jar log4j-1.2.16.jar * commons-logging.jar * * @author hoojo * @createDate 2011-4-21 下午07:57:26 * @file CastorTest.java * @package com.hoo.test * @project WebHttpUtils * @blog http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com * @version 1.0 */ public class CastorTest { private Account bean = null; private Mapping mapping = new Mapping(); private StringWriter writer = null; private StringReader reader = null; @Before public void init() { bean = new Account(); bean.setAddress("北京"); bean.setEmail("email"); bean.setId(1); bean.setName("jack"); Birthday day = new Birthday(); day.setBirthday("2010-11-22"); bean.setBirthday(day); try { /** * 加载mapping.xml,此文件是对需要转换的Java对象的配置描述, 即:转换后的Java对象的xml内容的转换规则 */ mapping.loadMapping(System.getProperty("user.dir") + "\\src\\main\\java\\mapping.xml"); // mapping.loadMapping("\\" + "mapping.xml"); } catch (IOException e) { e.printStackTrace(); } catch (MappingException e) { e.printStackTrace(); } } @After public void destory() { bean = null; mapping = null; try { if (writer != null) { writer.flush(); writer.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } System.gc(); } public void fail(Object o) { System.out.println(o); } public void failRed(Object o) { System.err.println(o); } /** * <b>function:</b>将Javabean编组,转换成XML * * @author hoojo * @createDate 2011-4-22 下午12:08:48 */ @Test public void writeBean2XML() { writer = new StringWriter(); try { // 编组 Marshaller.marshal(bean,writer); fail(writer); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>将List转换成xml * * @author hoojo * @createDate 2011-4-22 下午12:11:00 */ @Test public void writeList2XML() { writer = new StringWriter(); List<Account> list = new ArrayList<Account>(); list.add(bean); Account bean2 = new Account(); bean2.setName("tom"); bean2.setId(223); list.add(bean2); try { Marshaller.marshal(list,writer); fail(writer); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>将Array数组转换成XML * * @author hoojo * @createDate 2011-4-22 下午12:11:25 */ @Test public void writeArray2XML() { writer = new StringWriter(); Account[] acc = new Account[2]; acc[0] = bean; bean = new Account(); bean.setName("tom"); bean.setId(223); acc[1] = bean; try { Marshaller.marshal(acc,writer); fail(writer); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>将Java常用类型编组成xml * * @author hoojo * @createDate 2011-4-22 下午12:11:44 */ @Test public void writeObject2XML() { writer = new StringWriter(); try { Marshaller.marshal(true,writer); Marshaller.marshal(9527,writer); Marshaller.marshal(2.2f,writer); Marshaller.marshal(1.11d,writer); Marshaller.marshal("lucy",writer); Marshaller.marshal("hello castor".getBytes(),writer); Marshaller.marshal(new char[] { 'a','b','c' },writer); Marshaller.marshal(new String[] { "hi","spring","castor" },writer); fail(writer); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>将XML内容,解组成JavaBean * * @author hoojo * @createDate 2011-4-22 下午12:12:14 */ @Test public void readXML2Bean() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<account id=\"1\"><address>北京</address>" + "<name>jack</name><email>email</email>" + "<birthday><birthday>2010-11-22</birthday></birthday></account>"; reader = new StringReader(xml); try { // 解组 Account account = (Account) Unmarshaller.unmarshal(Account.class,reader); fail(account); } catch (MarshalException e) { e.printStackTrace(); } catch (ValidationException e) { e.printStackTrace(); } } /** * <b>function:</b>将XML内容解组成Java对象 * * @author hoojo * @createDate 2011-4-22 下午12:13:28 */ @Test public void bean4Mapping2XML() { writer = new StringWriter(); try { // 编组 Marshaller mar = new Marshaller(writer); mar.setMapping(mapping); mar.marshal(bean); fail(writer); // 解组 reader = new StringReader(writer.toString()); Unmarshaller unmar = new Unmarshaller(Account.class); unmar.setMapping(mapping); Account account = (Account) unmar.unmarshal(reader); fail(account); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } @Test public void readBean4Mapping2XML() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Account id=\"2241\"><name>jack</name><email>email</email><address>北京</address><生日 birthday=\"2010-11-22\"/></Account>"; try { reader = new StringReader(xml); Unmarshaller unmar = new Unmarshaller(Account.class); unmar.setMapping(mapping); Account account = (Account) unmar.unmarshal(reader); fail(account); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>将XML内容解组成Java的Array * * @author hoojo * @createDate 2011-4-22 下午12:14:50 */ @Test public void array4Mapping2XML() { writer = new StringWriter(); Account[] acc = new Account[2]; acc[0] = bean; bean = new Account(); bean.setName("tom"); bean.setId(223); acc[1] = bean; AccountArray array = new AccountArray(); array.setAccounts(acc); try { Marshaller mar = new Marshaller(writer); mar.setMapping(mapping); mar.marshal(array); fail(writer); reader = new StringReader(writer.toString()); Unmarshaller unmar = new Unmarshaller(AccountArray.class); unmar.setMapping(mapping); array = (AccountArray) unmar.unmarshal(reader); fail(array.getSize()); fail(array.getAccounts()[0]); fail(array.getAccounts()[1]); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>xml转换成Java的Map * * @author hoojo * @createDate 2011-4-22 下午12:15:18 */ @Test public void map4Mapping2XML() { writer = new StringWriter(); MapBean mapBean = new MapBean(); Map<String,Object> map = new HashMap<String,Object>(); map.put("No1",bean); bean = new Account(); bean.setName("tom"); bean.setId(223); map.put("No2",bean); mapBean.setMap(map); try { Marshaller mar = new Marshaller(writer); mar.setMapping(mapping); mar.marshal(mapBean); fail(writer); reader = new StringReader(writer.toString()); Unmarshaller unmar = new Unmarshaller(MapBean.class); unmar.setMapping(mapping); mapBean = (MapBean) unmar.unmarshal(reader); fail(mapBean.getMap()); } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * <b>function:</b>List到XML的相互转换 * * @author hoojo * @createDate 2011-4-22 下午12:16:04 */ @Test public void listForMapping2XML() { writer = new StringWriter(); List<Account> list = new ArrayList<Account>(); list.add(bean); bean = new Account(); bean.setName("tom"); bean.setId(223); list.add(bean); ListBean listBean = new ListBean(); listBean.setList(list); try { Marshaller mar = new Marshaller(writer); mar.setMapping(mapping); mar.marshal(listBean); fail(writer); reader = new StringReader(writer.toString()); Unmarshaller unmar = new Unmarshaller(ListBean.class); unmar.setMapping(mapping); listBean = (ListBean) unmar.unmarshal(reader); fail(listBean.getList().size()); for (Account acc : (List<Account>) listBean.getList()) { fail(acc); } } catch (MarshalException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
3,运行结果:
<?xml version="1.0" encoding="UTF-8"?> <map-bean><map xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com" xsi:type="java:org.exolab.castor.mapping.MapItem"><key xsi:type="java:java.lang.String">No2</key><value id="223" xsi:type="Account"><name>tom</name></value></map><map xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com" xsi:type="java:org.exolab.castor.mapping.MapItem"><key xsi:type="java:java.lang.String">No1</key><value id="1" xsi:type="Account"><name>jack</name><email>email</email><address>北京</address><生日 birthday="2010-11-22"/></value></map></map-bean> {No2=223#tom#null#null#null,No1=1#jack#email#北京#2010-11-22} <?xml version="1.0" encoding="UTF-8"?> <list-bean><list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="1" xsi:type="Account"><name>jack</name><email>email</email><address>北京</address><生日 birthday="2010-11-22"/></list><list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="223" xsi:type="Account"><name>tom</name></list></list-bean> 2 1#jack#email#北京#2010-11-22 223#tom#null#null#null <?xml version="1.0" encoding="UTF-8"?> <account-array size="2"><accounts id="1"><name>jack</name><email>email</email><address>北京</address><生日 birthday="2010-11-22"/></accounts><accounts id="223"><name>tom</name></accounts></account-array> 2 1#jack#email#北京#2010-11-22 223#tom#null#null#null <?xml version="1.0" encoding="UTF-8"?> <boolean>true</boolean><?xml version="1.0" encoding="UTF-8"?> <integer>9527</integer><?xml version="1.0" encoding="UTF-8"?> <float>2.2</float><?xml version="1.0" encoding="UTF-8"?> <double>1.11</double><?xml version="1.0" encoding="UTF-8"?> <string>lucy</string><?xml version="1.0" encoding="UTF-8"?> <[-b>aGVsbG8gY2FzdG9y</[-b><?xml version="1.0" encoding="UTF-8"?> <array><character>a</character><character>b</character><character>c</character></array><?xml version="1.0" encoding="UTF-8"?> <array><string>hi</string><string>spring</string><string>castor</string></array> <?xml version="1.0" encoding="UTF-8"?> <Account id="1"><name>jack</name><email>email</email><address>北京</address><生日 birthday="2010-11-22"/></Account> 1#jack#email#北京#2010-11-22 2241#jack#email#北京#2010-11-22 <?xml version="1.0" encoding="UTF-8"?> <array><account id="1"><address>北京</address><email>email</email><name>jack</name><birthday><birthday>2010-11-22</birthday></birthday></account><account id="223"><name>tom</name></account></array> <?xml version="1.0" encoding="UTF-8"?> <account id="1"><address>北京</address><email>email</email><name>jack</name><birthday><birthday>2010-11-22</birthday></birthday></account> 1#jack#email#北京#2010-11-22 <?xml version="1.0" encoding="UTF-8"?> <array-list><account xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com" id="1" xsi:type="java:com.hoo.entity.Account"><address>北京</address><email>email</email><name>jack</name><birthday><birthday>2010-11-22</birthday></birthday></account><account xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:java="http://java.sun.com" id="223" xsi:type="java:com.hoo.entity.Account"><name>tom</name></account></array-list>4,git源代码地址: [url]https://git.oschina.net/coderdream/castor-demo [/url] 5,源代码下载: 原文链接:https://www.f2er.com/xml/296329.html