用DOM来解析、修改、删除XML

package com.mgear.domparse;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
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("d:\\magical123.xml");
Document d = db.parse(f);
TransformerFactory tfFac = TransformerFactory.newInstance();
Transformer tf = tfFac.newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING,"gb2312");
tf.setOutputProperty(OutputKeys.INDENT,"yes");
StreamResult result = new StreamResult(System.out);
DOMSource source = new DOMSource(d);
System.out.println("修改前的XML:");
tf.transform(source, result);
System.out.println();

// 打印元素名称和文本值
u.read(d);

// 为书名为"java basic"的作者增加属性sex
u.add(d, "java basic", "sex", "man");

// 修改书名为"java basic"的作者为"magicalboy"
u.update(d, "java basic", "magicalboy");

// 删除书名为"java basic"的作者元素
u.delete(d, "java basic");
System.out.println("修改后的XML:");
tf.setOutputProperty("encoding", "GB2312");
tf.transform(source, result);
// 保存修改后的xml文件
tf.transform(source, new StreamResult(
new File("d:\\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(
"d:\\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");
Node n;
Element author;
for (int i = 0; i < nl.getLength(); i++) {
n = nl.item(i);
author = (Element) n.getNextSibling().getNextSibling();
if (title.equals(n.getFirstChild().getNodeValue())) {
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().getNodeValue();
// System.out.println(strNode);
// strNode = n.getFirstChild().getNodeValue();
// System.out.println(strNode);
if (title.equals(strNode)) {
Element Eauthor = (Element) e.getNextSibling()
.getNextSibling();
System.out.println("修改前的Author:"
+ Eauthor.getFirstChild().getNodeValue());
Eauthor.getFirstChild().setNodeValue(author);
System.out.println("修改后的Author:"
+ Eauthor.getFirstChild().getNodeValue());
}
}
} 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.getNodeValue();
// 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().getNodeValue());
e.getFirstChild().getNextSibling().removeChild(
nl.item(i).getNextSibling().getNextSibling());
System.out.println("删除成功!");
}
}
} catch (Exception ee) {
ee.printStackTrace();
}
}
}
转载自:http://6377936.blog.163.com/blog/static/3922283420094213950566/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值