xml工具

package com.runqianapp.p3.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants; 
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException; 
import javax.xml.xpath.XPathFactory; 
 
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import org.w3c.dom.NodeList;

public class XMLUtil {
 
 //private static String xmlFile;

 /**
   * @param filePath
   *   所要读的xml文件路径
   * @return
   *   该xml文件的根节点
   * @throws IOException
   * @throws JDOMException
   */
 public static Element readXML(String filePath) throws IOException,JDOMException {
  SAXBuilder builder = new SAXBuilder(); //实例JDOM解析器
  Document document = null;           //读取xml文件
  Element root = null;   
  try {   
   document = builder.build(filePath);    //将xml文档转换成document对象
   System.out.println(filePath);
   root = document.getRootElement();     //获取文档的根元素
  } catch (JDOMException e) {
   e.printStackTrace();
   throw e;
  } catch (IOException e) {
   e.printStackTrace();
   throw e;
  }
  return root;
 }
 
 /**
  * 遍历所有节点查找指定条件的节点 并根据信息作相应的操作
  * @param node
  *            头节点
  * @param searchStr
  *            查找的内容
  * @param type
  *            做相应的操作:修改、删除
  * @param updateCont
  *            修改的内容
  */
 public static void researchXmlNode(Element node, String searchStr,String type, String updateCont) {
  String nodeName;
  String nodeAttributeValue;
  Element elem;
  //遍历全部节点
  for (int i = 0; i < node.getChildren().size(); i++) {
   elem = (Element) node.getChildren().get(i);
   nodeName = (elem).getName();
   nodeAttributeValue = (elem).getAttributeValue("name");
   if("update".equals(type)){
    if (nodeName.equals(searchStr)) {// 修改节点
     (elem).setAttribute("name",updateCont);
    }
   } else if ("delete".equals(type)) {// 删除节点
    if (nodeAttributeValue.contains(searchStr)) {
     (elem).removeContent();
    }
   }
   researchXmlNode(elem, searchStr,type, updateCont);
  }
 }
 
  /**
  * 添加指定元素标识名称的元素
  * @param document
  *    要添加元素的文档模型
  * @param elementName
  *    要添加的元素标识名称
  * @param parentElementPath
  *    父节点
  * @return
  * @throws Exception
  */
 
  public static  void addElement(Object document,String parentElementPath,String elementName) throws Exception{
   try {
    Element parentElement;
    parentElement=(Element)XPath.selectSingleNode(document,parentElementPath);
    Element newElement=new Element(elementName);
    parentElement.addContent(newElement);
   } catch (Exception ex){
    ex.printStackTrace();
    throw ex;
   }
  }
 
 /**
 * @param filePath
 *            xml文件路径
 * @param modifyNode
 *            要修改内容的节点名称
 * @param modifyNewContent
 *            要修改成的内容
 * @param type
 *            做相应的操作:增加、修改、删除
 * @throws Exception
 *
 */
 public static void dealXml(String filePath, String modifyNode,String modifyNewContent, String type)
   throws Exception {
  
  Element root = readXML(filePath);
  researchXmlNode(root, modifyNode, type, modifyNewContent);
  saveXML(xmlFile,filePath);
 }
 
 /**
     * doc2XmlFile
     * 将Document对象保存为一个xml文件到本地
     * @return true:保存成功   flase:失败
     * @param filename 保存的文件名
     * @param document 需要保存的document对象
     * @throws Exception
     */
   public static boolean saveXml(String xmlFile,String filename) throws Exception
    {
    boolean flag = true;
    try {
     /* 将document中的内容写入文件中 */
     //默认为UTF-8格式,指定为"GB2312"
     OutputFormat format = OutputFormat.createPrettyPrint();
     format.setEncoding("GB2312");
     XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)),format);
     writer.write(xmlFile);
     writer.close();            
    } catch (Exception e) {
     flag = false;
     e.printStackTrace();
     throw e;
      }
    return flag;      
    }
 
 /**
  * xpath,查询节点
  * @param xmlFile
  *    xml文件
  * @return 节点属性
  *
  */
   public static Object searchNode(String xmlFile){   
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    File file=new File(xmlFile);
    Document doc = builder.parse(file);    //此处为文件存放相对路径

    XPathFactory newfactory = XPathFactory.newInstance();  //创建 XPathFactory
    XPath xpath = newfactory.newXPath();
    XPathExpression expr = xpath.compile("//*[ends-with(name(),'B')]");    // 使用这个工厂创建 XPath 对象
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList)result;
    for (int i = 0; i < nodes.getLength(); i++) {
    // System.out.println(nodes.item(i).getNodeValue());
    }
    return result;
   }
}

 

 

 

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值