“用dom4j解析包”对xml进行dom方式操作--ReadXML

来源:互联网 发布:c语言零基础入门书籍 编辑:程序博客网 时间:2024/05/06 05:37

IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结!

package edu.dom4j.dom;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Iterator;

import java.util.List;

import org.dom4j.Attribute;

import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.Node;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;

import org.junit.Test;

/**

 * 1.读取指定标签的Text

 * 2.读取指定标签的属性

 * 3.将product.xml文档分别以Pretty print(漂亮)和  

 *   Compact format(压缩)风格 打印到 System.out和file

 * 注意:由于这里对中文未作处理,所以打印到控制台和xml文件中的中文会乱码,

 *       具体处理方式见:dom4j工具修改xml文件时中文乱码解决方案

 * 4.通过递归方法,将document对象的xml结构输出

 **/

public class ReadXML {

  private String xmlfile = "WebRoot/product2.xml";

  private  Attribute attribute;

  private Node node ;


  public Document getDocument () throws DocumentException {

  //获得dom4j解析器

  SAXReader reader = new SAXReader();

  //读取xml文档:注意是org.dom4j.Document包下

  Document document = reader.read(xmlfile);

  return document;

  }

  /*

   * 读取第二个<product>标签中的<specifications>桌椅</specifications>的Text

   * 但是这对于Text也是标签,是不能读取的

   */

  @Test

  public void readXmlText() throws DocumentException{

  Document document = getDocument();

  //得到xml文档的根节点

  Element root = document.getRootElement();

  //得到root节点下<product>子节点集合,用elements(name)方法

  List<Element> products = root.elements("product");

  //得到对二个<product>节点

  Element product2 = products.get(1);

  //因为pruduct2下只有一个specifications标签,故用element(name)方法

  Element specifications = product2.element("specifications");

  //取得specifications节点的Text

  String text = specifications.getText();

  

  System.out.println("<specifications>"+text+"</specifications>");

  //输出结果:<specifications>桌椅</specifications>

  }

  //读取读取第一个<product>标签的category和inventory属性值

  @Test

  public void readXmlAttr() throws DocumentException{

   Document document = getDocument();

   Element root = document.getRootElement();

   Element product1 = root.element("product");

   //获得指定属性值方式一:获得Attribute对象  

   Attribute categoryAttr = product1.attribute("category");

   System.out.print("<product "+categoryAttr.getName()+"='"+categoryAttr.getValue()+"'");

    //获得指定属性方式二:直接获得Attribute属性值

   String categoryValue = product1.attributeValue("inventory");

   System.out.println(" inventory='"+categoryValue+"'>");

  }

  //将product.xml文档分别以Pretty print(漂亮)和  Compact format(压缩)风格 打印到 System.out和file

  @Test

  public void formatXml2system() throws DocumentException, IOException{

   Document document = getDocument();

   /*

    * 对内存中document对象进行CRUD操作代码

    * ......

    */

   //1.将document对象更新至product2.xml或新建xml

   XMLWriter writer = new XMLWriter(new FileWriter("WebRoot/product3.xml"));

   writer.write(document);

  //可以调用writer.close(),关闭的同时,调用了writer.flush(),但是中文的话,会出现乱码

   writer.flush();

   //2.将domcument对象以Pretty print的方式打印到 System.out

   OutputFormat format = OutputFormat.createPrettyPrint();

   writer = new XMLWriter(System.out,format);

   writer.write(document);

   writer.flush();

   //3.将document对象以Compact format的方式打印到System.out

   format = OutputFormat.createCompactFormat();

   writer = new XMLWriter(System.out,format);

   writer.write(document);

   writer.flush();

  }

  //通过递归方法,将document对象的xml结构输出

  @Test

  public void printXml2system() throws DocumentException{

   Element root = getDocument().getRootElement();

   printElement(root);

  }

  //打印参数节点信息,循环参数节点的子节点,递归调用该方法,输出element节点的结构

  public void printElement(Element element){

   System.out.print("<"+element.getName());

   //迭代输出标签element上的属性

   for(Iterator<Attribute> i = element.attributeIterator();i.hasNext();){

    attribute = i.next();

     System.out.print(" "+attribute.getName()+"='"+attribute.getValue()+"'");

   }

   System.out.print(">");

   //循环element的子节点

    for (int j = 0,size = element.nodeCount(); j < size; j++) {

    node = element.node(j);

     if (node instanceof Element) {

           System.out.println();

           printElement((Element)node);

      }else {

            /*

             * 这里的.trim()方法必须要,因为dom4j解析时,

             *  结束标签和下一个开始标签之间的空格也是一个对象

             */

          System.out.print(node.getText().trim());

      }

    }

    System.out.println("<"+element.getName()+"/>");

  }

}


product2.xml文件:

<?xml version="1.0" encoding="utf-8"?>

<catalog id="cata1">

   <product category="HandTool" inventory="InStock">

      <specifications weight="2.0kg">扳手</specifications>

      <price street="香港街">80.0</price>

      <notes>这是扳手</notes>

   </product>

   <product category="Table">

       <specifications>桌椅</specifications>

       <price street="澳门街" wholesale="部分">100.0</price>

   </product>

</catalog>





原创粉丝点击