Java Dom对XML的解析和修改操作
与Dom4J和JDom对XML的操作类似,JDK提供的JavaDom解析器用起来一样方便,在解析XML方面Java DOM甚至更甚前两者一筹!其不足之处在于对XML的增删改比较繁琐,特开篇介绍...
1、XML文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<address-book>
<contact id="01" type="家庭" >
<name>张三</name>
<address>黄山路666号</address>
<city>阜阳</city>
<province>安徽</province>
<postalcode>236000</postalcode>
<country>中国</country>
<telephone>18056075816</telephone>
</contact>
<contact id="02" type="商务" >
<name>李四</name>
<address>望江西路888号</address>
<city>合肥</city>
<province>安徽</province>
<postalcode>230091</postalcode>
<country>中国</country>
<telephone>13956921922</telephone>
</contact>
<contact id="03" type="同学" >
<name>王五</name>
<address>民主路3号</address>
<city>贵港市</city>
<province>广西</province>
<postalcode>537111</postalcode>
<country>中国</country>
<telephone>13965131384</telephone>
</contact>
<address-book>
2、与XML对应的域对象如下:
public class Contact
{
private String id;
private String type;
private String name;
private String address;
private String city;
private String privince;
private String postalcode;
private String country;
private String telephone; public Contact(String id, String type, String name, String address,
String city, String privince, String postalcode, String country,
String telephone)
{
this.id = id;
this.type = type;
this.name = name;
this.address = address;
this.city = city;
this.privince = privince;
this.postalcode = postalcode;
this.country = country;
this.telephone = telephone;
} public Contact()
{ } //省略Set Get方法 }
3、解析XML的过程
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList; public class ParseXML
{
List<Contact> contacts = new ArrayList<Contact>(); public List<Contact> getContacts()
{
return contacts;
} public ParseXML() throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("YellowBook.xml"); XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
NodeList nodes = (NodeList) xPath.evaluate("/address-book/contact", doc, XPathConstants.NODESET);
for(int i=0;i<nodes.getLength();i++)
{
Node node=nodes.item(i);
this.contacts.add(nodeToContact(node));
}
} public Contact nodeToContact(Node node) throws Exception
{
XPathFactory xpf = XPathFactory.newInstance();
XPath xPath = xpf.newXPath();
String id=(String) xPath.evaluate("@id", node,XPathConstants.STRING);
String type=(String) xPath.evaluate("@type", node,XPathConstants.STRING);
String name=(String) xPath.evaluate("name", node,XPathConstants.STRING);
String address=(String) xPath.evaluate("address", node,XPathConstants.STRING);
String city=(String) xPath.evaluate("city", node,XPathConstants.STRING);
String province=(String) xPath.evaluate("province", node,XPathConstants.STRING);
String postalcode=(String) xPath.evaluate("postalcode", node,XPathConstants.STRING);
String country=(String) xPath.evaluate("country", node,XPathConstants.STRING);
String telephone=(String) xPath.evaluate("telephone", node,XPathConstants.STRING);
Contact c=new Contact(id, type, name, address, city, province, postalcode, country, telephone);
return c;
}
}
4、对XML操作以及序列化的过程
import java.io.FileOutputStream;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
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; public class SerializeXML
{
public void serializeXML(String id) throws Exception
{
Scanner sc=new Scanner(System.in);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("YellowBook.xml"); NodeList nodes=doc.getElementsByTagName("contact");
for(int i=0;i<nodes.getLength();i++)
{
Element e=(Element) nodes.item(i);
if(e.getAttribute("id").equals(id))
{
System.out.println("输入类型:");
String type=sc.nextLine();
e.setAttribute("type", type); NodeList childNodes=e.getChildNodes();
for(int j=0;j<childNodes.getLength();j++)
{
Node childNode=(Node) childNodes.item(j);
if(childNode.getNodeName().equals("name"))
{
System.out.println("输入姓名:");
String name=sc.nextLine();
childNode.setTextContent(name);
}
}
}
} TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();
DOMSource domSource=new DOMSource(doc);
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
StreamResult result=new StreamResult(new FileOutputStream("YellowBook.xml"));
transformer.transform(domSource, result);
}
}
5、涉及业务逻辑的处理
import java.util.List; public class ContactService
{
public Contact findById(String id) throws Exception
{
ParseXML xml=new ParseXML();
List<Contact> contacts=xml.getContacts();
Contact con=new Contact();
for(Contact c:contacts)
{
if(c.getId().equals(id))
{
con=c;
}
}
return con;
} public void updateById(String id) throws Exception
{
SerializeXML serializeXML=new SerializeXML();
serializeXML.serializeXML(id);
}
}
6、测试
public class Main
{
public static void main(String[] args) throws Exception
{
ContactService contactDao=new ContactService();
Contact con=contactDao.findById("01");
System.out.println(con.getName()); contactDao.updateById("02");
}
}
Java Dom对XML的解析和修改操作的更多相关文章
- EasyUI加zTree使用解析 easyui修改操作的表单回显方法 验证框提交表单前验证 datagrid的load方法
带参提交一次查询,从服务器加载新数据.这是一个神奇的方法 $('#dg').datagrid('load',{ code: '01', name: 'name01' }); easyui修改操作的回显 ...
- JAva使用DOM读取XML数据(解析)
原来一切都是有套路的 使用DOM解析XML文档步骤 1.创建解析器工厂对象 DocumentBuildFactory对象 2.由解析器工厂对象创建解析器对象,即DocumentBuilder对象 3. ...
- [ java 工具类] xml字符串解析成Map(DOM解析)
package com.tencent.jungle.wechat.util; import com.google.inject.Singleton; import org.w3c.dom.Docum ...
- Dom生成Xml和解析Xml
xml这样的文件格式在非常多时候都是非常适合我们用来存取数据的,所以利用程序来生成xml文件和解析xml文件就显得比較重要了.在dom中是把每个元素都看做是一个节点Node的,全部页面上的属性.元素等 ...
- org.w3c.dom(java dom)解析XML文档
位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会不理想 首先来了解点Java DOM 的 API:1.解析 ...
- 精讲 org.w3c.dom(java dom)解析XML文档
org.w3c.dom(java dom)解析XML文档 位于org.w3c.dom操作XML会比较简单,就是将XML看做是一颗树,DOM就是对这颗树的一个数据结构的描述,但对大型XML文件效果可能会 ...
- 9.XML文件解析
一.XML简介 XML(EXtensible Markup Language),可扩展标记语言 特点:XML与操作系统.编程语言的开发平台无关 实现不同系统之间的数据交换 作用:数据交互 配置应用程序 ...
- java对excel文件内容读写修改操作
Read.java package domain; import java.io.FileInputStream; import java.io.InputStream; import jxl.Cel ...
- xml&dom_sax&dom4j的常见操作
<? xml version =”1.0” encoding=”GB2312”?> <!-- 学生信息—><?xml-stylesheet type=”text/css” ...
随机推荐
- struts2针对mvc的框架 spring针对解耦与事务的框架
struts2针对mvc的框架 spring针对解耦与事务的框架
- DAY4-Python学习笔记
1.XML: 操作XML有两种方法:DOM和SAX DOM:把整个XML读入内存,解析为树,因此占用内存大,解析慢,优点是可以任意遍历树的节点 SAX:是流模式,边读边解析,占用内存小,解析快,缺点是 ...
- P3216 [HNOI2011]数学作业
题目描述 小 C 数学成绩优异,于是老师给小 C 留了一道非常难的数学作业题: 给定正整数 N 和 M ,要求计算Concatenate (1 .. N) Mod M 的值,其中 Concatenat ...
- metasploit出错信息:can't allocate memory
出现不能分配内存的原因: 1.postgresql服务未启动 启动服务 service postgresql start 2.虚拟机内存分配过小,如:512M 将kali虚拟机的内存扩展到1G 出错图 ...
- 【BZOJ2813】奇妙的Fibonacci
Description Fibonacci数列是这样一个数列: F1 = 1, F2 = 1, F3 = 2 . . . Fi = Fi-1 + Fi-2 (当 i >= 3) pty忽 ...
- 洛谷 P1270 “访问”美术馆 解题报告
P1270 "访问"美术馆 题目描述 经过数月的精心准备,Peer Brelstet,一个出了名的盗画者,准备开始他的下一个行动.艺术馆的结构,每条走廊要么分叉为两条走廊,要么通向 ...
- yum报错Segmentation fault
yum install 安装一个包,提示 Segmentation fault,可以确定的是这个源肯定是可用的. 经查询,是 libz 这个库存在多个版本,导致冲突. # ldconfig -v | ...
- pg中删除的页是否仍被访问
昨天看到微信群中,有人提问:pg对于标记为删除的页,是否会扫描到? 今天做了一下测试,发现如果删除的是表的最后连续的几个页(根据ctid来确定数据插入先后,只讨论有insert的情况)中的数据,最后几 ...
- 用递归的方法求一个数组的前n项和
用递归的方法求一个数组的前n项和 public class Demo1 { /* * 用递归的方法求一个数组的前n项和 */ public static void main(String[] args ...
- linux命令总结之lsof命令
简介 lsof(list open files)是一个列出当前系统打开文件的工具.在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件.所以如传输控 ...