鸿 网 互 联 www.68idc.cn

当前位置 : 服务器租用 > 手机系统开发 > J2ME > >

dom4j解析xml实例

来源:互联网 作者:佚名 时间:2015-09-25 05:37
test.xml ? xml version = "1.0" encoding = "GBK" ? rss version = "2.0" channel title 社区通知 / title link / description 社区通知 / description item id = "1" title 标题1 / title link 1 / link description 通知内容1 / description pubDate 发布

test.xml

<?xml version="1.0" encoding="GBK"?>

<rss version="2.0">
  <channel>
    <title>社区通知</title>
    <link/>
    <description>社区通知</description>
    <item id="1">
      <title>标题1</title>
      <link>1</link>
      <description>通知内容1</description>
      <pubDate>发布时间1(yyyy-MM-dd hh:mm:ss)</pubDate>
    </item>
    <item id="2">
      <title>标题2</title>
      <link>1</link>
      <description>通知内容2</description>
      <pubDate>发布时间2(yyyy-MM-dd hh:mm:ss)</pubDate>
    </item>
    <item id="3">
      <title>标题3</title>
      <link>1</link>
      <description>通知内容3</description>
      <pubDate>发布时间3(yyyy-MM-dd hh:mm:ss)</pubDate>
    </item>
  </channel>
</rss>

XmlDom4J.java

package com.jy.util;


import java.util.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.DocumentHelper;
import org.dom4j.Attribute;

public class XmlDom4J {
    
     //通过xml文件名得到DOM

     public Document getDocument(String xmlFileName) throws DocumentException {
         SAXReader reader = new SAXReader();
         Document d = reader.read(new File(xmlFileName));
         return d;
     }
    
     //重载,通过xml文件内容得到DOM

     public Document getDocument(String xmlContent, boolean b) throws
         DocumentException {
         Document d = DocumentHelper.parseText(xmlContent);
         return d;
     }
    
     //输出字符串

     public String transformDOM(Document d) {
         String xmlContent = "";
         xmlContent = d.asXML();
         return xmlContent;
     }
    
    //得到节点数量

    @SuppressWarnings("unchecked")
    public int nodeNum(Element parentEle, String childName) {
        if(parentEle == null)
            return 0;
        return parentEle.elements(childName).size();
     }
        
    //得到节点数量

    @SuppressWarnings("unchecked")
    public int nodeNum(Element parentEle, String nodeName, String attrName) {
         int num = 0;
         Iterator nodeIter = parentEle.elementIterator(nodeName);
         Element nodeEle = null;
         while (nodeIter.hasNext()) {
             nodeEle = (Element)nodeIter.next();
             Iterator attrIter = nodeEle.attributeIterator();
             while(attrIter.hasNext()) {
                 Attribute nameAttribute = (Attribute)attrIter.next();
                 if (nameAttribute.getName().equals(attrName)) {
                     num++;
                 }
             }
         }
         return num;
     }
    
     //重载,得到节点

     public Element getNode(Document d, String eleName) {
         Element ele = (Element) d.selectSingleNode(eleName);
         return ele;
     }
    
     //增加节点

     public void addNode(Element parentEle, String eleName, String eleValue) {
         Element newEle = parentEle.addElement(eleName);
         newEle.setText(eleValue);
     }
    
     //增加属性节点

     public void addAttribute(Element ele, String attributeName,
         String attributeValue) {
         ele.addAttribute(attributeName, attributeValue);
     }
    
     //删除节点

     @SuppressWarnings("unchecked")
    public void removeNode(Element parentEle, String attrName, String attrValue) {
         Iterator iter = parentEle.elementIterator();
         Element delEle = null;
         while (iter.hasNext()) {
             Element tmp = (Element) iter.next();
             if (tmp.getName().equals(attrName) && tmp.getText().equals(attrValue)) {
                 delEle = tmp;
             }
         }
         if (delEle != null) {
             parentEle.remove(delEle);
         }
     }
    
     //删除第一个节点

     @SuppressWarnings("unchecked")
    public void removeFirstNode(Element parentEle, String nodeName, String attrName) {
         Iterator nodeIter = parentEle.elementIterator(nodeName);
         Element delEle = null;
         while (nodeIter.hasNext()) {
             delEle = (Element)nodeIter.next();
             Iterator attrIter = delEle.attributeIterator();
             while(attrIter.hasNext()) {
                 Attribute nameAttribute = (Attribute)attrIter.next();
                 if (nameAttribute.getName().equals(attrName)) {
                     parentEle.remove(delEle);
                     return;
                 }
             }
         }
     }
    
     //删除节点

     @SuppressWarnings("unchecked")
    public void removeNode(Element parentEle, String nodeName, String attrName, String attrValue) {
         Iterator nodeIter = parentEle.elementIterator(nodeName);
         Element delEle = null;
         while (nodeIter.hasNext()) {
             delEle = (Element)nodeIter.next();
             Iterator attrIter = delEle.attributeIterator();
             while(attrIter.hasNext()) {
                 Attribute nameAttribute = (Attribute)attrIter.next();
                 if (nameAttribute.getName().equals(attrName) && nameAttribute.getText().equals(attrValue)) {
                     parentEle.remove(delEle);
                 }
             }
         }
     }
    
     //删除属性

     public void removeAttr(Element ele, String attributeName) {
         Attribute att = ele.attribute(attributeName);
         ele.remove(att);
     }
    
     //修改节点值

     public void setNodeText(Element ele, String newValue) {
         ele.setText(newValue);
     }
    
     //修改属性值

     public void setAttribute(Element ele, String attributeName,
         String attributeValue) {
         Attribute att = ele.attribute(attributeName);
         att.setText(attributeValue);
     }
    
    //写xml到本地

     public void writeToXml(String fileName, Document document, String encoding) throws IOException {
         OutputFormat format = OutputFormat.createPrettyPrint();
         format.setEncoding(encoding);
         XMLWriter output = new XMLWriter(
             new FileWriter(new File(fileName)), format);
         output.write(document);
         output.close();
     }
}

NoteRssXml.java

package com.jy.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.tree.DefaultDocument;

/**
 * <p>Title:NoteRssXml.java</p>
 * <p>Description:</p>
 * <p>Copyright:Copyright (c) 2009</p>
 * <p>Company:佳誉科技有限公司</p>
 *
 * @author 吴瑜明
 * @version Revision:1.0 Date:May 4, 2009
 */

public class NoteRssXml {
    public static final Log LOG = LogFactory.getLog(NoteRssXml.class);
    
    private final static String RSS = "rss";
    private final static String VERSION = "version";
    private final static String VERSIONVALUE = "2.0";
    private final static String CHANNEL = "channel";
    private final static String TITLE = "title";
    private final static String TITLEVALUE = "社区通知";
    private final static String LINK = "link";
    private final static String LINKVALUE = "";
    private final static String DESCRIPTION = "description";
    private final static String DESCRIPTIONVALUE = "社区通知";

    private final static String ITEM = "item";
    private final static String ITEMID = "id";
    private final static String ITEMTITLE = "title";
    private final static String ITEMTLINK = "link";
    private final static String ITEMTDESCRIPTION = "description";
    private final static String ITEMTDPUBDATE = "pubDate";
    
    private final static String Encoding = "GBK";
    private XmlDom4J xmlDom4J;
    
    public NoteRssXml() {
        xmlDom4J = new XmlDom4J();
    }
    
    /**
     * 功能说明:创建Document
     * @author fisher
     * @param fileName 文件路径
     * @return
     * */

    public void createDocument(String fileName){
         Document document = new DefaultDocument();
         Element rssElement = document.addElement(RSS);
     rssElement.addAttribute(VERSION, VERSIONVALUE);
    
     Element channelElement = rssElement.addElement(CHANNEL);
    
     Element titleElement = channelElement.addElement(TITLE);
     titleElement.setText(TITLEVALUE);
    
     Element linkElement = channelElement.addElement(LINK);
     linkElement.setText(LINKVALUE);
    
     Element descriptionElement = channelElement.addElement(DESCRIPTION);
     descriptionElement.setText(DESCRIPTIONVALUE);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
     }
    
    /**
     * 功能说明:增加元素
     * @author fisher
     * @param fileName 文件路径
     * @param idValue item节点的id值
     * @param titleValue item节点的title值
     * @param linkValue item节点的link值
     * @param descriptionValue item节点的description值
     * @param pubdateValue item节点的pubdate值
     * @return
     * */

    @SuppressWarnings("unchecked")
    public void addElement(String fileName, String id, String title,
            String link, String description, String pubdate) {
        Document document = null;
        try {
            document = xmlDom4J.getDocument(fileName);
        } catch (DocumentException e1) {
            LOG.error("get document fail...");
            LOG.error(e1.getMessage());
        }
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return;
        
     Element itemElement = channelElement.addElement(ITEM);
     itemElement.addAttribute(ITEMID, id);
     Element titleElement = itemElement.addElement(ITEMTITLE);
     titleElement.setText(title);
     Element linkElement = itemElement.addElement(ITEMTLINK);
     linkElement.setText(link);
     Element descriptionElement = itemElement.addElement(ITEMTDESCRIPTION);
     descriptionElement.setText(description);
     Element pubDateElement = itemElement.addElement(ITEMTDPUBDATE);
     pubDateElement.setText(pubdate);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
    }
    
    /**
     * 功能说明:增加元素
     * @author fisher
     * @param fileName 文件路径
     * @param document 文档
     * @param idValue item节点的id值
     * @param titleValue item节点的title值
     * @param linkValue item节点的link值
     * @param descriptionValue item节点的description值
     * @param pubdateValue item节点的pubdate值
     * @return
     * */

    @SuppressWarnings("unchecked")
    public void addElement(String fileName, Document document, String idValue, String titleValue,
            String linkValue, String descriptionValue, String pubdateValue) {
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return;
        
     Element itemElement = channelElement.addElement(ITEM);
     itemElement.addAttribute(ITEMID, idValue);
     Element titleElement = itemElement.addElement(ITEMTITLE);
     titleElement.setText(titleValue);
     Element linkElement = itemElement.addElement(ITEMTLINK);
     linkElement.setText(linkValue);
     Element descriptionElement = itemElement.addElement(ITEMTDESCRIPTION);
     descriptionElement.setText(descriptionValue);
     Element pubDateElement = itemElement.addElement(ITEMTDPUBDATE);
     pubDateElement.setText(pubdateValue);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
    }
    
    /**
     * 功能说明:初始化id,将id值设置为1-20
     * @author fisher
     * @param fileName 文件路径
     * @param nodeName 节点名称("//item/@id")
     * @return
     * */

    @SuppressWarnings("unchecked")
    public void initId(String fileName, String nodeName) {
        Document document = null;
        try {
            document = xmlDom4J.getDocument(fileName);
        } catch (DocumentException e1) {
            LOG.error("get document fail...");
            LOG.error(e1.getMessage());
        }
       List list = document.selectNodes(nodeName);
       //创建一个迭代器.

       Iterator iter = list.iterator();
       int id = 1;
       while (iter.hasNext()) {
         Attribute attribute = (Attribute) iter.next();
           //设置属性的值

           attribute.setValue("" + id);
           id++;
        }
       
      try {
             xmlDom4J.writeToXml(fileName, document, Encoding);
         } catch (IOException e) {
             LOG.error("write to xml fail...");
             LOG.error(e.getMessage());
         }
    }

    /**
     * 功能说明:初始化id,将id值设置为1-20
     * @author fisher
     * @param fileName 文件路径
     * @param nodeName 节点名称("//item/@id")
     * @return
     * */

    @SuppressWarnings("unchecked")
    public void initId(String fileName, Document document, String nodeName) {     
       //使用XPATH表达式从article元素中获得level节点列表

      /* List list = document.selectNodes("//item/@id");*/
       List list = document.selectNodes(nodeName);
       //创建一个迭代器.

       Iterator iter = list.iterator();
       int id = 1;
       while (iter.hasNext()) {
         //获得level节点的属性

         Attribute attribute = (Attribute) iter.next();
           //设置属性的值

           attribute.setValue("" + id);
           id++;
        }
       
      try {
             xmlDom4J.writeToXml(fileName, document, Encoding);
         } catch (IOException e) {
             LOG.error("write to xml fail...");
             LOG.error(e.getMessage());
         }
      }

    /**
     * 功能说明:修改节点ID
     * @author fisher
     * @param fileName 文件路径
     * @param nodeName 节点名称("//item/@id")
     * @param newid 新ID值
     * @param oldid 旧ID值
     * @return
     * */

    @SuppressWarnings("unchecked")
    public void modifXMLByNodeId(String fileName, String nodeName, String newid, String oldid) {
        Document document = null;
        try {
            document = xmlDom4J.getDocument(fileName);
        } catch (DocumentException e1) {
            LOG.error("get document fail...");
            LOG.error(e1.getMessage());
        }
        
       //使用XPATH表达式从article元素中获得level节点列表

      /* List list = document.selectNodes("//item/@id");*/
       List list = document.selectNodes(nodeName);
       //创建一个迭代器.

       Iterator iter = list.iterator();
       while (iter.hasNext()) {
         //获得level节点的属性

         Attribute attribute = (Attribute) iter.next();
         if (attribute.getValue().equals(oldid))
           //设置属性的值

           attribute.setValue(newid);
        }
       
      try {
             xmlDom4J.writeToXml(fileName, document, Encoding);
         } catch (IOException e) {
             LOG.error("write to xml fail...");
             LOG.error(e.getMessage());
         }
      }

    /**
     * 功能说明:修改节点ID
     * @author fisher
     * @param fileName 文件路径
     * @param document 文档
     * @param nodeName 节点名称("//item/@id")
     * @param newid 新ID值
     * @param oldid 旧ID值
     * @return
     * */

    @SuppressWarnings("unchecked")
    public void modifXMLByNodeId(String fileName, Document document, String nodeName, String newid, String oldid) {
       //使用XPATH表达式从article元素中获得level节点列表

       /* List list = document.selectNodes("//item/@id");*/
       List list = document.selectNodes(nodeName);
       //创建一个迭代器.

       Iterator iter = list.iterator();
       while (iter.hasNext()) {
         //获得level节点的属性

         Attribute attribute = (Attribute) iter.next();
         if (attribute.getValue().equals(oldid))
           //设置属性的值

           attribute.setValue(newid);
        }
      try {
             xmlDom4J.writeToXml(fileName, document, Encoding);
          } catch (IOException e) {
             LOG.error("write to xml fail...");
             LOG.error(e.getMessage());
          }
     }

    /**
     * 功能说明:移除第一个Item节点
     * @author fisher
     * @param fileName 文件路径
     * @return
     * */

     public void removeFirstItem(String fileName) {
        Document document = null;
        try {
            document = xmlDom4J.getDocument(fileName);
        } catch (DocumentException e1) {
            LOG.error("get document fail...");
            LOG.error(e1.getMessage());
        }
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return;
        
        xmlDom4J.removeFirstNode(channelElement, ITEM, ITEMID);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
    }

    /**
     * 功能说明:移除第一个Item节点
     * @author fisher
     * @param fileName 文件路径
     * @param document 文档
     * @return
     * */
    
    public void removeFirstItem(String fileName, Document document) {
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return;
        
        xmlDom4J.removeFirstNode(channelElement, ITEM, ITEMID);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
    }
    
    /**
     * 功能说明:通过节点ID移除Item节点
     * @author fisher
     * @param fileName 文件路径
     * @param document 文档
     * @param idValue ID值
     * @return
     * */

    public void removeItemById(String fileName, Document document, String idValue) {
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return;
        
        xmlDom4J.removeNode(channelElement, ITEM, ITEMID, idValue);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
    }
    
    /**
     * 功能说明:通过节点ID移除Item节点
     * @author fisher
     * @param fileName 文件路径
     * @param idValue ID值
     * @return
     * */

    public void removeItemById(String fileName, String idValue) {
        Document document = null;
        try {
            document = xmlDom4J.getDocument(fileName);
        } catch (DocumentException e1) {
            LOG.error("get document fail...");
            LOG.error(e1.getMessage());
        }
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return;
        
        xmlDom4J.removeNode(channelElement, ITEM, ITEMID, idValue);

     try {
            xmlDom4J.writeToXml(fileName, document, Encoding);
        } catch (IOException e) {
            LOG.error("write to xml fail...");
            LOG.error(e.getMessage());
        }
    }

    /**
     * 功能说明:获取节点个数
     * @author fisher
     * @param fileName 文件路径
     * @return
     * */

    public int getItemNum(String fileName) {
        Document document = null;
        try {
            document = xmlDom4J.getDocument(fileName);
        } catch (DocumentException e1) {
            LOG.error("get document fail...");
            LOG.error(e1.getMessage());
        }
        
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return 0;
        return xmlDom4J.nodeNum(channelElement, ITEM);
    }
    
    /**
     * 功能说明:获取节点个数
     * @author fisher
     * @param document 文档
     * @return
     * */

    public int getItemNum(Document document) {
        /**获取channel节点**/
        Element channelElement = xmlDom4J.getNode(document, "//" + CHANNEL);
        if(channelElement == null)
            return 0;
        return xmlDom4J.nodeNum(channelElement, ITEM, ITEMID);
    }
    
    public static void main(String[] args) {
        NoteRssXml noteRssXml = new NoteRssXml();
        /*noteRssXml.createDocument("D:/test.xml");
        noteRssXml.addElement("D:/test.xml", "1",
                "标题3", "", "通知内容1", "发布时间1(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.addElement("D:/test.xml", "2",
                "标题3", "", "通知内容2", "发布时间2(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.addElement("D:/test.xml", "3",
                "标题3", "", "通知内容3", "发布时间3(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.addElement("D:/test.xml", "4",
                "标题3", "", "通知内容2", "发布时间2(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.addElement("D:/test.xml", "5",
                "标题3", "", "通知内容3", "发布时间3(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.addElement("D:/test.xml", "6",
                "标题3", "", "通知内容2", "发布时间2(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.addElement("D:/test.xml", "7",
                "标题3", "", "通知内容3", "发布时间3(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.removeItemById("D:/test.xml", "1");
        noteRssXml.removeFirstItem("D:/test.xml");
        noteRssXml.addElement("D:/test.xml", "9",
                "标题3", "1", "通知内容3", "发布时间3(yyyy-MM-dd hh:mm:ss)");
        noteRssXml.modifXMLByNodeId("D:/test.xml", "//item/@id", "10", "9");*/

        noteRssXml.initId("D:/test.xml", "//item/@id");
        System.out.println(noteRssXml.getItemNum("D:/test.xml"));
    }
    
}

相关资料:Dom4j下载及使用Dom4j读写XML简介

网友评论
<