Dom4j操作XML实战,解析和插入XML实例
本例子是用XML来代替数据库的,XML的每个节点代替数据库一行数据。
直说过程:
XML文件结构:定义了一个名为:User.xml的文件:
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="0001" name="小米" password="xiaomi" birthday="1980-09-03" nickname="小强"/>
</users>
定义一个XML操作的工具类:
获取XML文件路径的方法:
private static String fillpath=XmlUtill.class.getClassLoader().getResource("User.xml").getPath();
但是,由于fillpath的路径名称中包含中文,为了处理这个,需要做中文处理,加上:
private static String fillpath;
static {
fillpath=XmlUtill.class.getClassLoader().getResource("User.xml").getPath();
try {
fillpath = URLDecoder.decode(fillpath,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(fillpath);
}
工具类完整代码:
主要包含:获取Document和写入XML两个操作:
package com.Utill; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter; public class XmlUtill { private static String fillpath;
static {
fillpath=XmlUtill.class.getClassLoader().getResource("User.xml").getPath();
try {
fillpath = URLDecoder.decode(fillpath,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//System.out.println(fillpath);
}
//获取Document
public static Document getDocument() throws Exception
{
SAXReader reader=new SAXReader();
Document document=reader.read(new File(fillpath));
return document;
}
//将Document写入XML
public static void writToXml(Document document) throws IOException
{
OutputFormat format=OutputFormat.createPrettyPrint();
XMLWriter writer=new XMLWriter(new FileOutputStream(fillpath),format);
writer.write(document); format=OutputFormat.createPrettyPrint();
writer=new XMLWriter(System.out,format);
writer.write(document);
}
}
定义一个POJO:User
package com.domain;
import java.util.Date;
public class User {
private String id;
private String name;
private String password;
private Date birthday;
private String nickname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", birthday=" + birthday + ", nickname="
+ nickname + "]";
}
}
定义一个UserImpl类,用来对xml进行查询,新增操作,模拟数据库的查询和新增操作
package com.dao; import java.text.SimpleDateFormat;
import org.dom4j.Document;
import org.dom4j.Element; import com.Utill.XmlUtill;
import com.domain.User; public class UserDaoImpl { public void add(User user)
{
try {
Document document=XmlUtill.getDocument();
Element root=document.getRootElement(); Element user_tag=root.addElement("user");
user_tag.addAttribute("id", "0002");
user_tag.addAttribute("name", "华为");
user_tag.addAttribute("password","华为");
user_tag.addAttribute("birthday", user.getBirthday()==null?" ":user.getBirthday().toLocaleString());
user_tag.addAttribute("nickname", "大强"); XmlUtill.writToXml(document);
} catch (Exception e) {
e.printStackTrace();
} } public User find(String name,String password)
{
try { Document document;
document = XmlUtill.getDocument(); Element e=(Element) document.selectSingleNode("//user[@name='"+name+"' and @password='"+password+"']");
if(e==null)
return null;
User user=new User();
String date=e.attributeValue("birthday");
if(date==null||date.equals(""))
user.setBirthday(null);
else
{
//日期转换类
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM--dd");
user.setBirthday(df.parse(date));
} user.setId(e.attributeValue("id"));
user.setName(e.attributeValue("name"));
user.setPassword(e.attributeValue("password"));
user.setNickname(e.attributeValue("nickname")); System.out.println(user.toString());
return user;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
测试类,测试查询和新增功能:
package com.Test;
import java.util.Date;
import org.junit.jupiter.api.Test;
import com.dao.UserDaoImpl;
import com.domain.User; class UserTest { @Test
void testAdd() {
User user=new User();
user.setId("0002");
user.setName("华为");
user.setPassword("huawei");
user.setBirthday(new Date());
user.setNickname("大强"); UserDaoImpl dao=new UserDaoImpl();
dao.add(user);
} public void TestFind()
{
UserDaoImpl dao=new UserDaoImpl();
dao.find("小米", "xiaomi");
} }
Dom4j操作XML实战,解析和插入XML实例的更多相关文章
- python XML文件解析:用xml.dom.minidom来解析xml文件
python解析XML常见的有三种方法: 一是xml.dom.*模块,是W3C DOM API的实现,若需要处理DOM API则该模块很合适, 二是xml.sax.*模块,它是SAX API的实现,这 ...
- Spring MVC-视图解析器(View Resolverr)-XML视图解析器(Xml View Resolver)示例(转载实践)
以下内容翻译自:https://www.tutorialspoint.com/springmvc/springmvc_xmlviewresolver.htm 说明:示例基于Spring MVC 4.1 ...
- Mybatis源码解析,一步一步从浅入深(四):将configuration.xml的解析到Configuration对象实例
在Mybatis源码解析,一步一步从浅入深(二):按步骤解析源码中我们看到了XMLConfigBuilder(xml配置解析器)的实例化.而且这个实例化过程在文章:Mybatis源码解析,一步一步从浅 ...
- Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)
Android XML shape 标签使用详解 一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...
- python xml文件解析 及生成xml文件
#解析一个database的xml文件 """ <databaselist type="database config"> <dat ...
- [C# | XML] XML 反序列化解析错误:<xml xmlns=''> was not expected. 附通用XML到类解析方法
使用 XML 反化时出现错误: public static TResult GetObjectFromXml<TResult>(string xmlString) { TResult re ...
- JAVA基础-XML的解析
一.XML的概述 XML的全名为可扩展标记语言(Extensible Markup Language),XML的作用为:1.传输,2.存取数据,3.软件的配置文件.传输现在都用更轻量的Json,而存储 ...
- 【转载并整理】JAVA解析或生成xml的四种方法
参考文章 1:http://blog.csdn.net/clemontine/article/details/53011362 2:http://www.jb51.net/article/98456. ...
- xml解析 使用dom4j操作xml
使用dom4j操作xml 1 导入 dom4j,的jar包 2 指定要解析的XML文件 SAXReader sr=new SAXReader(); Document document= sr.r ...
随机推荐
- 洛谷 P1164 小A点菜
题目背景 uim神犇拿到了uoi的ra(镭牌)后,立刻拉着基友小A到了一家……餐馆,很低端的那种. uim指着墙上的价目表(太低级了没有菜单),说:“随便点”. 题目描述 不过uim由于买了一些辅(e ...
- GraphX中Pregel单源点最短路径(转)
原文链接:GraphX中Pregel单源点最短路径 GraphX中的单源点最短路径例子,使用的是类Pregel的方式. 核心部分是三个函数: 1.节点处理消息的函数 vprog: (VertexId ...
- asp.net mvc源码分析-ModelValidatorProviders 客户端的验证
几年写过asp.net mvc源码分析-ModelValidatorProviders 当时主要是考虑mvc的流程对,客户端的验证也只是简单的提及了一下,现在我们来仔细看一下客户端的验证. 如图所示, ...
- AOP AspectJ 字节码 语法 MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- Laravel应用性能调优
这次性能测试方案中用到的优化技巧主要基于 Laravel 框架本身及其提供的工具. 关闭应用debugapp.debug=false 缓存配置信息php artisan config:cache 缓存 ...
- Android -- ConditionVariable
线程操作经常用到wait和notify,用起来稍显繁琐,而Android给我们封装好了一个ConditionVariable类,用于线程同步.提供了三个方法block().open().close() ...
- 【Scala】Scala-Map使用方法
Scala-Map使用方法 scala map put_百度搜索 Scala中的Map使用例子 - CSDN博客 How to populate java.util.HashMap on the fl ...
- 转:使用RNN解决NLP中序列标注问题的通用优化思路
http://blog.csdn.net/malefactor/article/details/50725480 /* 版权声明:可以任意转载,转载时请标明文章原始出处和作者信息 .*/ author ...
- capwap学习笔记——初识capwap(一)
2 初识CAPWAP 2.1 CAPWAP简介 说了半天CAPWAP,连全称都还没说,汗-- CAPWAP--Control And Provisioning of Wireless Access P ...
- Android短信收到,语音播报
发送短信功能界面 /** * 发送短信Demo * * @description: * @author ldm * @date 2016-4-22 上午9:07:53 */ public class ...