java 操作xml 读取,修改,追加

import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;

public class XMLFile {
 private static Document document;
 private static String filename;

 @SuppressWarnings("static-access")
 public XMLFile(String filename) throws ParserConfigurationException {
  this.filename = filename;
  this.document = getDocument();
 }

 public static Document getDocument() throws ParserConfigurationException {
  return loadXml();
 }

 /**
  * 得到xml文档
  *
  * @param filename
  * @return
  * @throws ParserConfigurationException
  */
 public static Document loadXml() throws ParserConfigurationException {
  Document document = null;
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  File file = new File(filename);
  if (file.exists()) {
   try {
    document = builder.parse(filename);
    document.normalize();
   } catch (SAXException ex) {
    ex.printStackTrace();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }

  return document;
 }

 /**
  * 修改某个节点的内容,将 nodeName 的值修改为newNodeValue
  *
  * @param nodeName
  * @param newNodeValue
  * @throws ParserConfigurationException
  */
 public static void xmlUpdate(String nodeName, String newNodeValue)
   throws ParserConfigurationException {
  Node root = document.getDocumentElement();
  /** 如果root有子元素 */
  if (root.hasChildNodes()) {
   /** ftpnodes */
   NodeList ftpnodes = root.getChildNodes();
   /** 循环取得ftp所有节点 */
   for (int i = 0; i < ftpnodes.getLength(); i++) {
    NodeList ftplist = ftpnodes.item(i).getChildNodes();
    for (int k = 0; k < ftplist.getLength(); k++) {
     Node subnode = ftplist.item(k);
     if (subnode.getNodeType() == Node.ELEMENT_NODE
       && subnode.getNodeName() == nodeName) {
      subnode.getFirstChild().setNodeValue(newNodeValue);
     }
    }

   }
  }
  xml2File();
 }

 public static void xmlUpdateAppend(String code, String name, String time,
   String info) throws ParserConfigurationException {
  Node root = document.getDocumentElement();
  /** 如果root有子元素 */
  if (root.hasChildNodes()) {
   Node node = document.getElementsByTagName("weather-" + code)
     .item(0);
   if (node == null) {
    Node newChild = createNode(root, code, name, time, info);
    root.appendChild(newChild);
   }
  }
  xml2File();
 }

 /**
  * 写入xml文件
  *
  * @param code
  * @param time
  * @param info
  * @throws ParserConfigurationException
  */
 public static void xmlWrite(String code, String name, String time,
   String info) throws ParserConfigurationException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  document = builder.newDocument();
  Element root = document.createElement("weather");
  document.appendChild(root);

  createNode(root, code, name, time, info);

  xml2File();
 }

 public static Node createNode(Node root, String code, String name,
   String time, String info) {

  Element weatherCode = document.createElement("weather-" + code);
  weatherCode.setAttribute("value", code);
  root.appendChild(weatherCode);

  Element weatherName = document.createElement("name-" + code);
  weatherName.appendChild(document.createTextNode(name));
  weatherCode.appendChild(weatherName);

  Element weatherTime = document.createElement("time-" + code);
  weatherTime.appendChild(document.createTextNode(time));
  weatherCode.appendChild(weatherTime);

  Element weatherInfo = document.createElement("info-" + code);
  weatherInfo.appendChild(document.createTextNode(info));
  weatherCode.appendChild(weatherInfo);

  return weatherCode;
 }

 /**
  * 读取某个节点的内容
  *
  * @param nodename
  * @return
  */
 public String readNode(String nodename) {
  Node node = document.getElementsByTagName(nodename).item(0);
  return node.getTextContent();
 }

 /**
  * 读取某个节点的属性
  *
  * @param nodename
  * @param itemname
  * @return
  */
 public String readAttribute(String nodename, String itemname) {
  Node node = document.getElementsByTagName(nodename).item(0);
  return node.getAttributes().getNamedItem(itemname).getTextContent();
 }

 public String parseString(String str, String nodename, String itemname) {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder dber;
  try {
   dber = factory.newDocumentBuilder();
   str = "<xroot>" + str + "</xroot>";
   ByteArrayInputStream bais = null;
   try {
    bais = new ByteArrayInputStream(str.getBytes("UTF-8"));
    Document docf;
    try {
     docf = dber.parse(bais);
     Node node = docf.getElementsByTagName(nodename).item(0);
     return node.getAttributes().getNamedItem(itemname)
       .getTextContent();
    } catch (IOException ex) {
     ex.printStackTrace();
    } catch (SAXException ex) {
     ex.printStackTrace();
    }

   } catch (UnsupportedEncodingException uee) {
    uee.printStackTrace();
   }
  } catch (ParserConfigurationException ex) {
   ex.printStackTrace();
  }
  return "";
 }

 /**
  * 将xml文件保存成文件
  */
 public static void xml2File() {
  try {
   TransformerFactory tf = TransformerFactory.newInstance();
   Transformer transformer = tf.newTransformer();
   DOMSource source = new DOMSource(document);
   transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
   PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
   StreamResult result = new StreamResult(pw);
   transformer.transform(source, result);
  } catch (TransformerException mye) {
   mye.printStackTrace();
  } catch (IOException exp) {
   exp.printStackTrace();
  }
 }

 public static void main(String[] args) {
  try {
   
   XMLFile xf = new XMLFile("./res/xml/weather-info.xml");
   if (xf.getDocument() == null) {
    // xf.xmlWrite("57038", "200898877", "43243143");
   }

   // xf.toUpdate("57038", "200898877", "43243143");
   Document d = xf.loadXml();
   System.out.println(d);
   // System.out.println();
   System.out.println("ok");
  } catch (ParserConfigurationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值