`

dom4j隨意記一下

阅读更多

package com.topthinking.tel.test.dom4j;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.xml.rpc.ServiceException;

import org.apache.axis.message.MessageElement;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;

import com._28tel.www.GetAllCurrencyResponseGetAllCurrencyResult;
import com._28tel.www.WebService_28TelLocator;
import com._28tel.www.WebService_28TelSoap;

public class ReadXMLByDom {
    public static void main(String [] args) throws DocumentException, ServiceException, IOException{
        ReadXMLByDom r = new ReadXMLByDom();
//        r.readXMLAllAttr();
//        r.readXMLAllElement();
//        r.readXMLAttr();
//        r.readXMLElement();
        
        
//        //遍历某节点下的一级节点
//        String str = "<diffgr><books><book id='1'><Name new = 'haha' >Java</Name><price>100</price><test>haoren</test></book>";
//        str = str + "<book id='2'><Name>Linux</Name><price>100</price></book></books></diffgr>";
//        Document document = DocumentHelper.parseText(str);
//        List list = document.selectNodes("/diffgr/books/book" );
//        Iterator it = list.iterator();
//        while(it.hasNext())
//        {
//            Element ftpElement = (Element)it.next();
//          //獲取指定節點的值
//          System.out.println("ftp_name="+ftpElement.element("Name").getText());
//          System.out.println("ftp_name="+ftpElement.element("price").getText());
//          //獲取指定節點的屬性值
//          System.out.println("指定屬性的值:"+ftpElement.element("Name").attributeValue("new"));
////            System.out.println("ftp_name="+ftpElement.elementIterator("test"));
//        }
        

    }
    
    //第一种:根据属性来查找
    //结果为:<book id="2"><Name>Linux</Name><price>100</price></book>
    public void readXMLAttr() {
        String str = "<books><book id='1'><Name>Java</Name><price>100</price></book>";
        str = str
                + "<book id='2'><Name>Linux</Name><price>100</price></book></books>";
        // 生成一个Document
        Document document = null;
        try {
            document = DocumentHelper.parseText(str);
            Element book = (Element) document
                    .selectSingleNode("/books/book[@id='2']");
            System.out.println(book.asXML());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    //第二种:根据节点名来查找
    //结果为:Java,Linux,
    public void readXMLElement() {
        String str = "<books><book id='1'><Name>Java</Name><price>100</price></book>";
        str = str
                + "<book id='2'><Name>Linux</Name><price>100</price></book></books>";
        Document document = null;
        try {
            document = DocumentHelper.parseText(str);
            List names = document.selectNodes("books/book/Name");// 记得这边是双斜杠且有区分大小写
            for (int i = 0; i < names.size(); i++) {
                System.out.print(((Element) names.get(i)).getText() + ",");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    //第三种:遍历整个XML取得属于指定类型节点的记录
    //结果为:1 Java 100
    //       2 Linux 100
    public void readXMLAllElement() {
//        String str = "<diffgr><NewDataSet><Table><UID>8613574286112</UID><Local_Number>86101756751060</Local_Number><Destination_Number>86123342545</Destination_Number><End_Time>2009-01-15T14:03:00+08:00</End_Time><Start_Time>2009-01-05T14:03:00+08:00</Start_Time><Opus>ADD</Opus><Amount>1</Amount></Table></NewDataSet></diffgr>";
        String str = "<books><book id='1'><Name>Java</Name><price>100</price></book>";
        str = str + "<book id='2'><Name>Linux</Name><price>100</price></book></books>";
        try {    
            Document document = null;
            document = DocumentHelper.parseText(str);
            Iterator it = document.getRootElement().elementIterator();
            Element element = null;
            while (it.hasNext()) {
                element = (Element) it.next();
                if (element.getName().equals("book")) {
                    System.out.print(element.attributeValue("id") + " ");
                    System.out.print(element.element("Name").getText() + " ");
                    System.out.println(element.element("price").getText());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    //第四种:遍历所有属性
    //结果为:id:1
    //       name:Java
    //       price:120
    public void readXMLAllAttr() {
        String str = "<book id='1' name='Java' price='120'/>";
//        String str = "<Table><UID>8613574286112</UID><Local_Number>86101756751060</Local_Number><Destination_Number>86123342545</Destination_Number><End_Time>2009-01-15T14:03:00+08:00</End_Time><Start_Time>2009-01-05T14:03:00+08:00</Start_Time><Opus>ADD</Opus><Amount>1</Amount></Table>";
        Document document;
        try {
            document = DocumentHelper.parseText(str);             
          Iterator attributes = document.getRootElement().attributeIterator();
            while (attributes.hasNext()) {
                Attribute attribute = (Attribute) attributes.next();
                System.out.println(attribute.getName() + ":"
                        + attribute.getValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}

分享到:
评论
1 楼 xuganggogo 2010-07-19  
备注:调用该方法之前,应该先向工程中添加支持xpath的jar包,否则,会出现以下错误:

java.lang.NoClassDefFoundError: org/jaxen/JaxenException
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectSingleNode(AbstractNode.java:183)
at xml_chb.dom4j_chb.getComplexInfofromDocument(dom4j_chb.java:82)
at xml_chb.dom4j_chb.main(dom4j_chb.java:92)
Exception in thread "main"

只需要引入jaxen包就行了,我使用的是hibernate包中的jaxen-1.1-beta-7.jar包。

相关推荐

Global site tag (gtag.js) - Google Analytics