<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架>
<书>
<书名 name="dddd">C语言程序设计</书名>
<作者>张孝祥</作者>
<售价>40</售价>
</书>
<书>
<书名>C++教程</书名>
<作者>自己</作者>
<售价>50</售价>
</书>
</书架>

  

package com.gbx.it;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StreamCorruptedException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
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.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; public class XMLDemo {
public String path = "src/book.xml";
/*
* 获得指定的Document
*/
public Document getDocument() throws ParserConfigurationException, SAXException, IOException {
//1: 获得dom解析工厂
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//2:获得dom解析
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//获得Document
Document document = documentBuilder.parse(path); return document;
}
/*
* 将XML文件由内存写入硬盘
*/
public void refreshXML(Source xmlSource, Result outputTarget) throws TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(xmlSource, outputTarget);
}
// ----------R------------------
/*
* 遍历DOM树
*/
@Test
public void read1() throws ParserConfigurationException, SAXException, IOException {
Document document = getDocument();
NodeList nodeList = document.getElementsByTagName("书架");
for (int i = 0; i < nodeList.getLength(); ++i) {
listNodes(nodeList.item(i));
}
}
private void listNodes(Node item) {
if (item instanceof Element) {
System.out.println(item.getNodeName());
}
NodeList nodeList = item.getChildNodes();
for (int i = 0; i < nodeList.getLength(); ++i) {
listNodes(nodeList.item(i));
}
}
/*
* 读取标签内的内容 <书名 name="dddd">java web就业</书名>
*/
@Test
public void read2() throws ParserConfigurationException, SAXException, IOException {
Document document = getDocument();
Element book = (Element) document.getElementsByTagName("书名").item(0);
String value = book.getTextContent();
System.out.println("书名: " + value);
}
/*
* 读取标签的属性
*/
@Test
public void read3() throws ParserConfigurationException, SAXException, IOException {
Document document = getDocument();
Element book = (Element) document.getElementsByTagName("书名").item(0);
if (book.hasAttributes()) {
NamedNodeMap nodeMap = book.getAttributes();
for (int i = 0; i < nodeMap.getLength(); ++i) {
String attrName = nodeMap.item(i).getNodeName();
String attrValue = nodeMap.item(i).getNodeValue();
System.out.println("name : " + attrName + " value :" + attrValue);
}
} String value = book.getAttribute("name");
System.out.println(value);
}
// ----------------C------------------- /*
* 添加标签 C
*/
//在指定标签的最后边添加标签
@Test
public void add1() throws ParserConfigurationException, SAXException, IOException, TransformerException {
Document document = getDocument();
Element book = (Element) document.getElementsByTagName("书").item(0);
Element newChild = document.createElement("你行");
newChild.setTextContent("嘿嘿");
book.appendChild(newChild); refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
}
//在指定标签的指定位置添加标签
@Test
public void add2() throws ParserConfigurationException, SAXException, IOException, TransformerException {
Document document = getDocument();
Element book = (Element) document.getElementsByTagName("书").item(0); Element newChild = document.createElement("你行");
newChild.setTextContent("嘿嘿"); Element refChild = (Element) document.getElementsByTagName("售价").item(0); book.insertBefore(newChild, refChild); refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
}
//添加属性
@Test
public void add3() throws ParserConfigurationException, SAXException, IOException, TransformerException {
Document document = getDocument(); Element e = (Element) document.getElementsByTagName("售价").item(0);
e.setAttribute("value", "RMB");
refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
}
//----------------D----------------
//删除标签
@Test
public void delElement() throws ParserConfigurationException, SAXException, IOException, TransformerException {
Document document = getDocument();
Element element = (Element) document.getElementsByTagName("你行").item(0);
element.getParentNode().removeChild(element);
refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
}
//删除标签的属性 @Test
public void delAttr() throws ParserConfigurationException, SAXException, IOException, TransformerException {
Document document = getDocument();
Element element = (Element) document.getElementsByTagName("售价").item(0);
element.removeAttribute("value");
refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
}
//-------------U------------
@Test
public void update() throws ParserConfigurationException, SAXException, IOException, TransformerException {
Document document = getDocument();
Element element = (Element) document.getElementsByTagName("书名").item(0);
element.setTextContent("C语言程序设计");
refreshXML(new DOMSource(document), new StreamResult(new FileOutputStream(path)));
}
}

  

参考:方立勋老师视频

DOM 操作XML(CRUD)的更多相关文章

  1. php中通过DOM操作XML

    DOM文档在js里早就接触过,知道DOM不但可以操作html文档,还可以操作XHTML,XML等文档,有着极强的通用性,下面我们通过两个小例子,看看在PHP中是如何用DOM操作XML文档的,和js中差 ...

  2. php : DOM 操作 XML

    DOM 操作 XML 基本用法 XML文件: person.XML <?xml version="1.0" encoding="utf-8" ?> ...

  3. Java用DOM操作xml

    JAXP DOM方式解析XML文档实例增删改查package jiexi; import javax.xml.parsers.DocumentBuilder; import javax.xml.par ...

  4. java使用DOM操作XML

    XML DOM简介 XML DOM 是用于获取.更改.添加或删除 XML 元素的标准. XML 文档中的每个成分都是一个节点. DOM 是这样规定的: 整个文档是一个文档节点 每个 XML 标签是一个 ...

  5. DOM操作XML文件

    一.IE中的XML(IE低版本才支持) 在统一的正式规范出来以前,浏览器对于 XML 的解决方案各不相同.DOM2 级提出了动态创建 XML DOM 规范,DOM3 进一步增强了 XML DOM. 所 ...

  6. PHP通过DOM操作XML

    PHP XML操作类DOMDocument属性及方法 注意大小写一定不能弄错. 属性: Attributes 存储节点的属性列表(只读) childNodes 存储节点的子节点列表(只读) dataT ...

  7. java DOM 操作xml

    1 代码如下: package dom.pasing; import java.io.IOException; import java.io.StringWriter; import javax.xm ...

  8. ajax——dom对xml和html的操作

    上篇文章说到了dom的基础,dom能够操作xml和html,这次主要写利用dom的api去如何去操作xml和html文档. dom操作xml dom操作xml文档之前必须把xml文档装载到xml do ...

  9. DOM【介绍、HTML中的DOM、XML中的DOM】

    什么是DOM? DOM(Document Object Model)文档对象模型,是语言和平台的中立接口. 允许程序和脚本动态地访问和更新文档的内容. 为什么要使用DOM? Dom技术使得用户页面可以 ...

随机推荐

  1. 我的Windows naked apps

    0. 驱动精灵全能网卡版 1. Microsoft Office 2010/2013 2. IE 11 3. Filezilla Client & Server 4. Google Chrom ...

  2. Xcode如何打包ipa安装包

    http://jingyan.baidu.com/article/ceb9fb10f4dffb8cad2ba03e.html

  3. [工具][windows][visualStudio][充电]番茄助手vaassist常见用法

    参考:http://blog.csdn.net/hotdog156351/article/details/43955565 1 安装好VAS打开VS2010之后,首先关闭VA outline与VA V ...

  4. 【转】表删除时 Cannot delete or update a parent row: a foreign key constraint fails 异常处理

    转载地址:http://lijiejava.iteye.com/blog/790478 有两张表,结构如下: t_item:                          t_bid: id    ...

  5. 【转】SVN提示:由于目标机器积极拒绝,无法连接 的解决方法

    转载地址:http://wxiaolei.blog.163.com/blog/static/1038760120133108180596/ 安装完TSVN之后,checkout时报错,并且后来在cmd ...

  6. c#多播委托

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...

  7. ROADS

    ROADS Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11977 Accepted: 4429 Description N ...

  8. K - Work 分类: 比赛 2015-07-29 19:13 3人阅读 评论(0) 收藏

    K - Work Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Sta ...

  9. ural 1104,暴力取模

    题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1104 题目大意:输入一个字符串(数字与大写字母组成),输出n,n满足此字符串为n进制时, ...

  10. ByteBuffer解析

    一.前言 前一篇文章我们介绍了Android中直播视频技术的基础大纲知识,这里就开始一一讲解各个知识点,首先主要来看一下视频直播中的一个重要的基础核心类:ByteBuffer,这个类看上去都知道了,是 ...