Chinaunix首页 | 论坛 | 博客
  • 博客访问: 141483
  • 博文数量: 19
  • 博客积分: 230
  • 博客等级: 二等列兵
  • 技术积分: 239
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-01 12:47
文章分类
文章存档

2014年(5)

2013年(4)

2012年(10)

分类: Java

2012-04-29 12:18:24

2012-04-29 10:14
    出差时间有点不规律,本想早点写的。
    先说dom4j,其实我也是个初学者,对于这个东西也不是很了解,只知道这个解析的效率最高。
代码可以参考IBM的文档个人觉得非常好。

点击(此处)折叠或打开

  1. public class XmlDom4J {

  2.     /**
  3.      * 生成xml文件
  4.      * @since 生成xml 具有一定的缩进格式
  5.      */
  6.     public void generateDocument() {
  7.         //使用 DocumentHelper 类创建一个文档实例。 DocumentHelper 是生成 XML 文档节点的 dom4j API 工厂类
  8.         Document document = DocumentHelper.createDocument();
  9.         //使用 addElement() 方法创建根元素 catalog 。 addElement() 用于向 XML 文档中增加元素
  10.         Element catalogElement = document.addElement("catalog");
  11.         //在 catalog 元素中使用 addComment() 方法添加注释“An XML catalog”。
  12.         catalogElement.addComment("An XML Catalog");
  13.         //在 catalog 元素中使用 addProcessingInstruction() 方法增加一个处理指令。
  14.         catalogElement.addProcessingInstruction("target", "text");    //还没弄清楚什么意思
  15.         //在 catalog 元素中使用 addElement() 方法增加 journal 元素
  16.         Element journalElement = catalogElement.addElement("journal");
  17.         //使用 addAttribute() 方法向 journal 元素添加 title 和 publisher 属性。
  18.         journalElement.addAttribute("title", "XML Zone");
  19.         //向 article 元素中添加 journal 元素。
  20.         journalElement.addAttribute("publisher", "IBM developerWorks");
  21.         Element articleElement = journalElement.addElement("article");
  22.         //为 article 元素增加 level 和 date 属性。
  23.         articleElement.addAttribute("level", "Intermediate");
  24.         articleElement.addAttribute("date", "December-2001");
  25.         //向article中添加title元素
  26.         Element titleElement = articleElement.addElement("title");
  27.         //使用 setText() 方法设置 article 元素的文本。
  28.         titleElement.setText("Java configuration with XML Schema");
  29.         //使用 setText() 方法设置 article 元素的文本。
  30.         Element authorElement = articleElement.addElement("author");
  31.         //在 article 元素中增加 author 元素.
  32.         Element firstNameElement = authorElement.addElement("firstname");
  33.         //在 author 元素中增加 firstname 元素并设置该元素的文本。
  34.         firstNameElement.setText("Marcello");
  35.         //在 author 元素中增加 lastname 元素并设置该元素的文本。
  36.         Element lastNameElement = authorElement.addElement("lastname");
  37.         lastNameElement.setText("Vitaletti");
  38.         /* 因为没有DTD文件,所以如果使用了,却没有文件,将解析出错 */
  39.         //可以使用 addDocType() 方法添加文档类型说明
  40. //        document.addDocType("catalog", null, "file://c:/Dtds/catalog.dtd");
  41.         try {
  42. //            String filePath = "D:\\catalog\\";
  43. //            String fileName = "catalog.xml";
  44. //            File file = estimateFile(filePath,fileName);
  45.             OutputFormat format = new OutputFormat(" ",true);    //控制输出的格式 indent:缩进, true: 开启
  46.             format.setEncoding("gb2312");
  47.             XMLWriter output = new XMLWriter(new FileWriter(new File("d:/catalog.xml")),format);
  48.             output.write(document);
  49.             output.close();
  50.         } catch (IOException e) {
  51.             System.out.println(e.getMessage());
  52.         }

  53.     }

我仿照文档写的基本没什么改动,解析的话用dom4j只要得到document就一步一步循环出来就可以了

点击(此处)折叠或打开

  1. SAXReader saxReader = new SAXReader();
  2.  Document document = saxReader.read(inputXml);

有的xml简单 有的xml复杂 复杂的话就需要考虑循环嵌套层数了想在ibm文档中使用的

点击(此处)折叠或打开

  1. List list = document.selectNodes("//article/@level" );

这种能够直接读取节点的方法需要一个额外的jaxen.jar包,才能有XPath支持。
    接下来说下jibx解析xml,用jibx解析好在它不只是为你解析,它可以做的更多。但你要想使用它也需要做的更多一点----绑定。
Customer对象

点击(此处)折叠或打开

  1. public class Customer {

  2.     public Person person;
  3.     public String street;
  4.     public String city;
  5.     public String state;
  6.     public Integer zip;
  7.     public String phone;
  8.     
  9.     
  10. }

Person对象

点击(此处)折叠或打开

  1. public class Person {

  2.     public int customerNumber;
  3.     public String firstName;
  4.     public String lastName;
  5.     
  6.     
  7. }

data.xml文件

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <customer>
  3. <person>
  4.     <cust-name>123456789 </cust-name>
  5.     <first-name>jhone</first-name>
  6.     <last-name>smith</last-name>
  7. </person>
  8. <street>12345 happy lane</street>
  9. <city>plunk</city>
  10. <state>WA</state>
  11. <zip>98059</zip>
  12. <phone>888.555.1234</phone>
  13. </customer>

binding.xml文件

点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <binding name="binding" package="org.daemonbelief.mythink.xmlhandle.xmlbean">
  3. <mapping name="customer" class="org.daemonbelief.mythink.xmlhandle.xmlbean.Customer">
  4.     <structure name="person" field="person" type="org.daemonbelief.mythink.xmlhandle.xmlbean.Person">
  5.         <value name="cust-name" field="customerNumber"/>
  6.         <value name="first-name" field="firstName"/>
  7.         <value name="last-name" field="lastName"/>
  8.         <!-- value style="text" field="lastName"/-->
  9.     </structure>
  10.     <value name="street" field="street"/>
  11.     <value name="city" field="city"/>
  12.     <value name="state" field="state"/>
  13.     <value name="zip" field="zip"/>
  14.     <value name="phone" field="phone"/>

  15. </mapping>
  16. </binding>


build_binding.xml文件

点击(此处)折叠或打开

  1. <?xml version="1.0"?>
  2. <project basedir="." default="bind">
  3.   
  4.   <!-- The following block is intended to set the jibx-home location. It first
  5.    checks the relative location of the JiBX libraries when this starter example
  6.    is run directly from the JiBX distribution, then (if that fails), looks for
  7.    an environmental variable JIBX_HOME with the installation path. If you prefer
  8.    to just set the path directly in this file, uncomment the following line and
  9.    set the value to the appropriate directory, then delete the rest of the Ant
  10.    commands down to the end of this block. -->
  11. <!-- <property name="jibx-home" value="jibx-home-directory-path"/> -->
  12.     <property file="build.properties"/>
  13.     <!--property name="jibx-home" value="${sourcedir}"/-->
  14.     <available file="${jibxhome}/lib/jibx-bind.jar" property="jibx-home" value="${sourcedir}"/>
  15.   <property environment="env"/>
  16.   <condition property="jibx-home" value="${sourcedir}">
  17.     <and>
  18.       <not>
  19.         <isset property="jibx-home"/>
  20.       </not>
  21.       <available file="${jibxhome}/lib"/>
  22.     </and>
  23.   </condition>
  24.   <!-- End of jibx-home location setting block. -->
  25.   
  26.   <!-- make sure required jars are present -->
  27.   <condition property="runtime-jars-found">
  28.     <available file="${jibxhome}/lib/jibx-run.jar"/>
  29.   </condition>
  30.   <condition property="binding-jars-found">
  31.     <and>
  32.       <available file="${jibxhome}/lib/bcel.jar"/>
  33.       <available file="${jibxhome}/lib/jibx-bind.jar"/>
  34.       <available file="${jibxhome}/lib/jibx-run.jar"/>
  35.     </and>
  36.   </condition>
  37.   
  38.   <!-- set classpath for compiling and running application with JiBX -->
  39.   <path id="classpath">
  40.     <fileset dir="${jibxhome}/lib" includes="*.jar"/>
  41.     <pathelement location="${jibxhome}/classes"/>
  42.   </path>
  43.   
  44.   <!-- make sure runtime jars are present -->
  45.   <target name="check-runtime">
  46.     <fail unless="jibx-home">JiBX home directory not found - define JIBX_HOME system property or set path directly in build.xml file.</fail>
  47.     <fail unless="runtime-jars-found">Required JiBX runtime jar jibx-run.jar was not found in JiBX home lib directory (${jibx-home}/lib)</fail>
  48.   </target>
  49.   
  50.   <!-- make sure binding jars are present -->
  51.   <target name="check-binding" depends="check-runtime">
  52.     <fail unless="binding-jars-found">Required JiBX binding jar jibx-bind.jar or bcel.jar was not found in JiBX home lib directory (${jibx-home}/lib)</fail>
  53.   </target>
  54.   
  55.   <!-- run the binding compiler -->
  56.   <target name="bind" depends="check-binding">
  57.     
  58.     <echo message="Running JiBX binding compiler"/>
  59.     <taskdef name="bind" classname="org.jibx.binding.ant.CompileTask">
  60.       <classpath>
  61.         <fileset dir="${jibxhome}/lib" includes="*.jar"/>
  62.       </classpath>
  63.     </taskdef>
  64.     <bind binding="${sourcedir}/WebContent/filefolder/binding.xml">
  65.       <classpath refid="classpath"/>
  66.     </bind>
  67.     
  68.   </target>

  69. </project>

build.properties文件

点击(此处)折叠或打开

  1. jibxhome=D:\\ProgramFiles\\workspace\\SHXY_YDJX_JIBX\\WebContent\\WEB-INF
  2. sourcedir=D:\\ProgramFiles\\workspace\\SHXY_YDJX_JIBX

首先要先写好Java对象和数据xml文件,然后用binding来绑定对象。绑定写好后就需要用ant运行build_binding.xml来生成两个bind的class,可以用Navigater视图看到。bind好后,下面的工作就简单了


点击(此处)折叠或打开

  1. public class Par***mlByJibx {

  2.     public static Object parseSourceXml(Class clazz,String filename){
  3.         IBindingFactory bindingfactory = null;
  4.         Customer customer = new Customer();
  5.         try {
  6.             bindingfactory = BindingDirectory.getFactory(clazz);/* 绑定工厂 */
  7.             IUnmarshallingContext unmarshallingcontext = bindingfactory.createUnmarshallingContext();/* 创建反编列的上下文 */
  8.             FileInputStream fis = new FileInputStream(new File(filename));/* 文件输入流 获取文件信息 */
  9.             customer = (Customer)unmarshallingcontext.unmarshalDocument(fis, null);/* 将'流'中的数据反编列得到相应的'对象' */
  10.             IMarshallingContext marshallingcontext = bindingfactory.createMarshallingContext();/* 创建编列的上下文 */
  11.             marshallingcontext.setIndent(2);/* 设置缩进 */
  12.             FileOutputStream fos = new FileOutputStream("parsetest.xml");/* 文件输出流 输出对象信息 */
  13.             marshallingcontext.marshalDocument(customer, "UTF-8",null,fos);/* 以指定编码编列'对象'到文件 */
  14.             
  15.         } catch (JiBXException e) {
  16.             e.printStackTrace();
  17.         } catch (FileNotFoundException e) {
  18.             e.printStackTrace();
  19.         }
  20.         return customer;
  21.         
  22.     }
  23. }

用jibx解析出来的就会直接将属性转换给对象。使用方便 绑定复杂。
jibx需要的jar包:ant-contrib.jar
                 ant.jar
                 antlr.jar
                 bcel.jar
                 jibx-bind.jar
                 jibx-extras.jar
                 jibx-run.jar
                 log4j-1.2.12.jar
                 xpp3.jar
因为bind比较复杂,弄了好久才绑定好。可以参考下官方文档
总结:对于如何解析复杂xml我不是很清楚,但这两种方式是比较实用,并且常用的。看情况和复杂程度来决定使用什么。没有最好的,只有更适合的。








阅读(3144) | 评论(0) | 转发(0) |
0

上一篇:解析json字符串

下一篇:java的泛型

给主人留下些什么吧!~~