对xml文档操作的常用方法

java 代码
  1.   
  2. import java.io.*;   
  3. import java.util.*;   
  4.   
  5. import javax.xml.XMLConstants;   
  6. import javax.xml.parsers.DocumentBuilder;   
  7. import javax.xml.parsers.DocumentBuilderFactory;   
  8. import javax.xml.transform.Source;   
  9. import javax.xml.transform.dom.DOMSource;   
  10. import javax.xml.transform.stream.StreamSource;   
  11. import javax.xml.validation.Schema;   
  12. import javax.xml.validation.SchemaFactory;   
  13. import javax.xml.validation.Validator;   
  14.   
  15. import org.dom4j.*;   
  16. import org.dom4j.io.*;   
  17. import org.xml.sax.SAXException;   
  18.   
  19. /**  
  20.  * name:XMLUtil.java  
  21.  *   
  22.  * desc: 本类是xml文档操作实用类,提供对xml文档操作的常用方法。  
  23.  *  
  24.  */  
  25.   
  26. public class XMLUtil   
  27. {   
  28.     private Document doc;   
  29.        
  30.     /**  
  31.      * 构造函数  
  32.      *  
  33.      */  
  34.     public XMLUtil()   
  35.     {   
  36.            
  37.     }   
  38.        
  39.     /**  
  40.      * 方法完成xml文件的加载,在调用本类的其他方法前需要调用loadFromFile()或者loadFromString()  
  41.      * @param file xml文件对象  
  42.      * @throws Exception  
  43.      */  
  44.     public void loadFromFile(File file)throws Exception   
  45.     {   
  46.         //参数无效   
  47.         if (file == null || !file.exists() || file.isDirectory())   
  48.         {   
  49.             throw new IllegalArgumentException("xml file is not valid!");   
  50.         }   
  51.         SAXReader saxReader = new SAXReader();   
  52.         doc = saxReader.read(file);   
  53.     }   
  54.        
  55.     /**  
  56.      * 方法完成xml格式字符串的加载,转换成xml文档形式,注意参数必须符合xml格式,  
  57.      * 否则后续操作会出错  
  58.      * @param contents xml格式的字符串  
  59.      * @throws Exception  
  60.      */  
  61.     public void loadFromString(String contents)throws Exception   
  62.     {   
  63.         //参数无效   
  64.         if (contents == null || contents.trim().length() == 0)   
  65.         {   
  66.             throw new IllegalArgumentException("argument is not valid!");   
  67.         }   
  68.         doc = DocumentHelper.parseText(contents);   
  69.     }   
  70.        
  71.     /**  
  72.      * 方法执行xml文档的保存  
  73.      * @param filePath xml文件保存路径  
  74.      * @param encoding xml文件编码格式(gb2312|utf-8|gbk等)  
  75.      * @throws IOException  
  76.      * @throws Exception  
  77.      */  
  78.     public void dump(String filePath, String encoding)throws IOException, Exception   
  79.     {   
  80.         //参数无效   
  81.         if (filePath == null || filePath.trim().length() == 0)   
  82.         {   
  83.             throw new IllegalArgumentException("store path is not valid!");   
  84.         }   
  85.         encoding = (encoding == null || encoding.trim().length() == 0) ? "gb2312" : encoding;   
  86.         OutputFormat format = OutputFormat.createPrettyPrint();   
  87.         format.setEncoding(encoding);   
  88.         format.setIndent("  ");   
  89.         FileWriter fileWriter = new FileWriter(filePath);   
  90.         XMLWriter xmlWriter = new XMLWriter(fileWriter, format);   
  91.         try  
  92.         {   
  93.             xmlWriter.write(doc);   
  94.         }   
  95.         catch(Exception e)   
  96.         {   
  97.             throw e;   
  98.         }   
  99.         finally  
  100.         {   
  101.             xmlWriter.close();   
  102.             xmlWriter = null;   
  103.             fileWriter.close();   
  104.             fileWriter = null;   
  105.         }   
  106.            
  107.     }   
  108.        
  109.        
  110.     /**  
  111.      * 方法获取单个指定节点名的节点  
  112.      * @param name 节点名,支持Xpath  
  113.      * @param index 节点出现的索引位置  
  114.      * @return 找到返回Element,没找到返回null.  
  115.      * @throws Exception  
  116.      */  
  117.     public Element getElement(String name, int index)throws Exception   
  118.     {   
  119.         //节点名无效   
  120.         if (!isValidate(name))   
  121.         {   
  122.             throw new IllegalArgumentException("the element's name is not valid!");   
  123.         }   
  124.            
  125.         //索引位置无效   
  126.         if (index < 0)   
  127.         {   
  128.             throw new IllegalArgumentException("the element's index is not valid!");   
  129.         }   
  130.         List elementsList = doc.selectNodes("//" + name);   
  131.            
  132.         //指定的节点名存在并且索引有效   
  133.         if (elementsList != null && elementsList.size() > index)   
  134.         {   
  135.             return (Element)elementsList.get(index);   
  136.         }   
  137.         return null;   
  138.     }   
  139.        
  140.     /**  
  141.      * 方法获取指定节点名的节点list  
  142.      * @param name 节点名  
  143.      * @return 节点list  
  144.      * @throws Exception  
  145.      */  
  146.     public ArrayList getElements(String name)throws Exception   
  147.     {   
  148.         //节点名无效   
  149.         if (!isValidate(name))   
  150.         {   
  151.             throw new IllegalArgumentException("element name is not valid!");   
  152.         }   
  153.         List list = doc.selectNodes("//" + name);   
  154.         ArrayList <Element>arrayList = new ArrayList<Element>();   
  155.         //存在节点时,循环获取每一个节点   
  156.         if (list != null)   
  157.         {   
  158.             int length = list.size();   
  159.             for (int i = 0; i < length; i++)   
  160.             {   
  161.                 Node node = (Node)list.get(i);   
  162.                    
  163.                 //节点是element实例时,添加到arrayList   
  164.                 if (node instanceof Element)   
  165.                 {   
  166.                     arrayList.add((Element)node);   
  167.                 }   
  168.             }   
  169.         }   
  170.         return arrayList;   
  171.     }   
  172.        
  173.     /**  
  174.      * 方法获取一个节点的子节点信息  
  175.      * @param element 节点  
  176.      * @param subElementName 子节点名称  
  177.      * @return 子节点list,每个list元素是一个Element  
  178.      * @throws Exception  
  179.      */  
  180.     public ArrayList getSubElements(Element element, String subElementName)throws Exception   
  181.     {   
  182.         //参数无效   
  183.         if (element == null)   
  184.         {   
  185.             throw new IllegalArgumentException("element is null!");   
  186.         }   
  187.            
  188.         //参数无效   
  189.         if (!isValidate(subElementName))   
  190.         {   
  191.             throw new IllegalArgumentException("sub element name is invalid!");   
  192.         }   
  193.         return (ArrayList)element.elements(subElementName);   
  194.     }   
  195.        
  196.     /**  
  197.      * 方法获取单个节点值  
  198.      * @param name 节点名  
  199.      * @return 节点值  
  200.      * @throws Exception  
  201.      */  
  202.     public String getElementValue(String name)throws Exception   
  203.     {   
  204.         //invalid argument   
  205.         if (!isValidate(name))   
  206.         {   
  207.             throw new IllegalArgumentException("argument is not valid!");   
  208.         }   
  209.         Node node = doc.selectSingleNode("//" + name);   
  210.            
  211.         //return the value   
  212.         if (node instanceof Element)   
  213.         {   
  214.             return node.getText().trim();   
  215.         }   
  216.         return "";   
  217.     }   
  218.        
  219.        
  220.     /**  
  221.      * 方法获取指定节点名的节点值的properties,重复的节点值将过滤掉  
  222.      * @param name 节点名  
  223.      * @return 节点值properties  
  224.      * @throws Exception  
  225.      */  
  226.     public Properties getElementValues(String name)throws Exception   
  227.     {   
  228.         if (!isValidate(name))   
  229.         {   
  230.             throw new IllegalArgumentException("elememt name is not valid!");   
  231.         }   
  232.         List elementList = doc.selectNodes("//" + name);   
  233.         Properties properties = new Properties();   
  234.         //节点存在   
  235.         if (elementList != null && elementList.size() > 0)   
  236.         {   
  237.                
  238.             int length = elementList.size();   
  239.             for (int i = 0; i < length; i++)   
  240.             {   
  241.                 String elementValue = ((Element)elementList.get(i)).getTextTrim();    
  242.                 properties.put(elementValue, elementValue);   
  243.             }   
  244.             return properties;   
  245.         }   
  246.         return properties;   
  247.     }   
  248.        
  249.     /**  
  250.      * 方法返回指定节点的属性信息  
  251.      * @param element 节点  
  252.      * @return 以name,value形式存在的属性  
  253.      * @throws Exception  
  254.      */  
  255.     public Properties getElementProperties(Element element)throws Exception   
  256.     {   
  257.         //参数无效   
  258.         if (element == null)   
  259.         {   
  260.             throw new IllegalArgumentException("element is null!");   
  261.         }   
  262.         List attributes = element.attributes();   
  263.         Properties properties = new Properties();   
  264.         for (int i = 0; i < attributes.size(); i++)   
  265.         {   
  266.             Attribute attr = (Attribute)attributes.get(i);   
  267.             properties.put(attr.getName(), attr.getValue());   
  268.         }   
  269.         return properties;   
  270.     }   
  271.        
  272.     /**  
  273.      * 方法返回节点的属性信息  
  274.      * @param elementName 节点名称  
  275.      * @return 以name,value形式存在的属性  
  276.      * @throws Exception  
  277.      */  
  278.     public Properties getElementProperties(String elementName)throws Exception   
  279.     {   
  280.         //参数无效   
  281.         if (!isValidate(elementName))   
  282.         {   
  283.             throw new IllegalArgumentException("element name is invalid!");   
  284.         }   
  285.         return this.getElementProperties(this.getElement(elementName, 0));   
  286.     }   
  287.        
  288.     /**  
  289.      * 方法执行节点名的更改  
  290.      * @param oldName 原始节点名  
  291.      * @param newName 更改后节点名  
  292.      * @param index 要更改的节点索引(索引指在xml文件中节点出现的位置)  
  293.      * @throws Exception  
  294.      */  
  295.     public void renameElement(String oldName, String newName, int index)throws Exception   
  296.     {   
  297.         //原始节点名无效   
  298.         if (!isValidate(oldName))   
  299.         {   
  300.             throw new IllegalArgumentException("original element name is not valid!");   
  301.         }   
  302.            
  303.         //新的节点名无效   
  304.         if (!isValidate(newName))   
  305.         {   
  306.             throw new IllegalArgumentException("new element name is not valid!");   
  307.         }   
  308.         Element element = getElement(oldName, index);   
  309.         //指定的节点不存在   
  310.         if (element == null)   
  311.         {   
  312.             throw new Exception("can not find element, which name is : " + oldName   
  313.                                   + " index is : " + index);   
  314.                
  315.         }   
  316.         element.setName(newName);   
  317.     }   
  318.        
  319.     /**  
  320.      * 方法执行节点名的更改  
  321.      * @param oldName 原始节点名  
  322.      * @param newName 更改后节点名  
  323.      * @throws Exception  
  324.      */  
  325.     public void renameElements(String oldName, String newName)throws Exception   
  326.     {   
  327.         //原始节点名无效   
  328.         if (!isValidate(oldName))   
  329.         {   
  330.             throw new IllegalArgumentException("original element name is not valid!");   
  331.         }   
  332.            
  333.         //新的节点名无效   
  334.         if (!isValidate(newName))   
  335.         {   
  336.             throw new IllegalArgumentException("new element name is not valid!");   
  337.         }   
  338.         ArrayList list = getElements(oldName);   
  339.            
  340.         //不存在该节点名   
  341.         if (list == null)   
  342.         {   
  343.             throw new Exception("can not find any element, which name is : " + oldName);   
  344.         }   
  345.            
  346.         //循环更改节点名   
  347.         int length = list.size();   
  348.         for (int i = 0; i < length; i++)   
  349.         {   
  350.             ((Element)list.get(i)).setName(newName);   
  351.         }   
  352.     }   
  353.        
  354.     /**  
  355.      * 方法执行子节点的添加,要添加的子节点必须存在父节点,添加子节点的属性可以为空。  
  356.      * @param parent 父节点名  
  357.      * @param index 父节点的索引(存在同名父节点时,在第index个父节点处添加子节点)  
  358.      * @param current 子节点名  
  359.      * @param currentValue 子节点值  
  360.      * @param attributes 子节点属性  
  361.      * @throws Exception  
  362.      */  
  363.     public void addSubElement(String parent, int index, String current, String currentValue,    
  364.                                 Properties attributes)throws Exception   
  365.     {   
  366.         //父节点无效   
  367.         if (!isValidate(parent))   
  368.         {   
  369.             throw new IllegalArgumentException("parent element is not valid!");   
  370.         }   
  371.            
  372.         //当前节点无效   
  373.         if (!isValidate(current))   
  374.         {   
  375.             throw new IllegalArgumentException("current element is not valid!");   
  376.         }   
  377.            
  378.         Element parentElement = getElement(parent, index);   
  379.            
  380.         //指定的父节点不存在   
  381.         if (parentElement == null)   
  382.         {   
  383.             throw new Exception("can not find the specified parent element, which name is :"  
  384.                                  + parent);   
  385.         }   
  386.         Element currentElement = parentElement.addElement(current);   
  387.            
  388.         //节点值有效   
  389.         if (currentValue != null && currentValue.length() > 0)   
  390.         {   
  391.             currentElement.setText(currentValue);   
  392.         }   
  393.            
  394.         //存在属性时,添加节点属性   
  395.         if (attributes != null)   
  396.         {   
  397.             Enumeration e = attributes.keys();   
  398.             while (e.hasMoreElements())   
  399.             {   
  400.                 Object attrName = e.nextElement();   
  401.                 Object attrValue = attributes.get(attrName);   
  402.                 currentElement.addAttribute(attrName.toString(), attrValue.toString());   
  403.             }   
  404.         }   
  405.     }   
  406.        
  407.     /**  
  408.      * 方法执行子节点的添加,要添加的子节点必须存在父节点,  
  409.      * @param parent 父节点名  
  410.      * @param index 父节点在xml文档中的索引  
  411.      * @param childList 子节点list,每个list元素是一个Element  
  412.      * @throws Exception  
  413.      */  
  414.     public void addSubElements(String parent, int index, ArrayList childList)   
  415.     throws Exception   
  416.     {   
  417.         Element parentElement = getElement(parent, index);   
  418.         //指定的父节点不存在   
  419.         
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值