posts - 57, comments - 4, trackbacks - 0, articles - 10
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
java写的用DOM来解析、修改、删除XML(2009-06-03 10:31:26)
标签:杂谈  分类:xml

magicalXML.java

package com.magicalxml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

public class magicalXML {
public static void main(String[] args) throws ParserConfigurationException {
   magicalXML u = new magicalXML();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
   try {
    //读取源文件,如果不存在就创建一个新的给它
    File f = new File("E:""XML""test""magical123.xml");
    Document d = db.parse(f);
    TransformerFactory tfFac = TransformerFactory.newInstance();
    Transformer tf = tfFac.newTransformer();
    tf.setOutputProperty("encoding","GB2312");
    StreamResult result = new StreamResult(System.out);
    DOMSource source = new DOMSource(d);
    System.out.println("修改前的XML:");
    tf.transform(source, result);
    System.out.println();
   
   
   
       
    System.out.println("修改后的XML:");
    tf.setOutputProperty("encoding","GB2312");
    tf.transform(source, result);
    //保存修改后的xml文件
    tf.transform(source, new StreamResult(new File(
    "E:""XML""test""magical123.xml")));

   } catch (SAXException e) {
    e.printStackTrace();
   } catch (FileNotFoundException e) {
    //创建xml
    Document dl = db.newDocument();
    u.create(dl);
   } catch (TransformerConfigurationException e) {
    e.printStackTrace();
   } catch (TransformerException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }

}
//创建方法
public void create(Document d) {
   Element pub = d.createElement("publication");
   Element book = d.createElement("book");
   Element title = d.createElement("Title");
   Element author = d.createElement("Author");
  
   title.appendChild(d.createTextNode("java basic"));
   author.appendChild(d.createTextNode("john"));
   book.appendChild(title);
   book.appendChild(author);
   pub.appendChild(book);
  
   book = d.createElement("book");
   title = d.createElement("Title");
   author = d.createElement("Author");
   title.appendChild(d.createTextNode("magicalbook"));
   author.appendChild(d.createTextNode("枫叶"));
  
   book.appendChild(title);
   book.appendChild(author);
   pub.appendChild(book);
   //增加到根节点
   d.appendChild(pub);
   try {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer f = tf.newTransformer();
    f.setOutputProperty("encoding","GB2312");
    System.out.println("正在创建新的xml...");
    f.transform(new DOMSource(d), new StreamResult(new File(
      "E:""XML""test""magical123.xml")));
    System.out.println("创建新的xml成功!新的xml如下:");
    f.transform(new DOMSource(d),new StreamResult(System.out));
   }
   catch (Exception e) {
    e.printStackTrace();
   }
}
//读取元素名称和文本值方法
public void read(Document d) {
   NodeList nl = d.getElementsByTagName("*"); // 取所有结点
   for (int i = 0; i < nl.getLength(); i++) {

    if (nl.item(i).getFirstChild().getNodeType() == Node.ELEMENT_NODE)
     System.out.println("元素名称:"+nl.item(i).getNodeName());
    else {
     System.out.println("元素名称:"+nl.item(i).getNodeName());
     System.out.println("文本值:"+nl.item(i).getTextContent());
    }
   }
}
//元素增加属性方法
public void add(Document d, String title, String attr, String value) {
   NodeList nl = d.getElementsByTagName("Title");
   Element el = d.getDocumentElement();
   Node n;
   Element author;
   String str;
   for(int i=0; i<nl.getLength(); i++) {
    n = nl.item(i);
    author = (Element)n.getNextSibling().getNextSibling();
    if(title.equals(n.getFirstChild().getNodue())) {
     System.out.println("为元素"+author.getNodeName()+"增加"+attr+"属性:"+value);
     author.setAttribute(attr, value);
     
   }
}
//修改方法
public void update(Document doc, String title, String author) {
   NodeList nl = doc.getElementsByTagName("Title");
   String strNode;
   Element e;
//   Node n;
   System.out.println("有"+nl.getLength()+"个book节点");
   try {
    for(int i = 0; i < nl.getLength(); i++) {
     e = (Element) nl.item(i);
//     n = nl.item(i);
     strNode = e.getFirstChild().getNodue();
//     System.out.println(strNode);
//     strNode = n.getFirstChild().getNodue();
//     System.out.println(strNode);
     if (title.equals(strNode)) {
      Element Eauthor = (Element) e.getNextSibling().getNextSibling();
      System.out.println("修改前的Author:"+Eauthor.getFirstChild().getNodue());
      Eauthor.getFirstChild().setNodue(author);
      System.out.println("修改后的Author:"+Eauthor.getFirstChild().getNodue());
     }
    }
   } catch (Exception ee) {
    ee.printStackTrace();
   }
}
//删除方法
public void delete(Document doc,String title) {
   NodeList nl = doc.getElementsByTagName("Title");
   Element e = doc.getDocumentElement();
   Node n;
   String strNode;
   //System.out.println(""n有"+nl.getLength()+"个Title节点");
   try {
    for(int i=0; i<nl.getLength(); i++) {
     n = nl.item(i).getFirstChild();
     strNode = n.getNodue();
//     System.out.println(e.getNodeName());
//     System.out.println(e.getFirstChild().getNextSibling().getNodeName());
//     System.out.println(nl.item(i).getNodeName());
//     System.out.println(strNode);
     if(("java basic").equals(strNode)) {
      System.out.println(""n准备要删除的书名为"+title+"的作者是:"+nl.item(i).getNextSibling().getNextSibling().getFirstChild().getNodue());
      e.getFirstChild().getNextSibling().removeChild(nl.item(i).getNextSibling().getNextSibling());
      System.out.println("删除成功!");
     }
    }
   } catch (Exception ee) {
    ee.printStackTrace();
   }
}
}

 

magical123.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?><publication>
<book>
   <Title>java basic</Title>
   <Author>john</Author>
</book>
<book>
   <Title>magicalbook</Title>
   <Author>magicalboy</Author>
</book>
</publication>

已投稿到: 排行榜 圈子

只有注册用户登录后才能发表评论。


网站导航: