JAVA 解析 XML
XML文件时很多项目经常使用的配置或者其他用途的文件格式,解析xml文件格式的开发包也很多,本文主要使用java自带的DOM解析包。本文以一个实际例子来讲述解析xml文件的过程。
目标:解析这样一个XML文件
employees.xml
=======内容开始========
<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
<Employee type="permanent">
<Name>Seagull</Name>
<Id>3674</Id>
<Age>34</Age>
</Employee>
<Employee type="contract">
<Name>Robin</Name>
<Id>3675</Id>
<Age>25</Age>
</Employee>
<Employee type="permanent">
<Name>Crow</Name>
<Id>3676</Id>
<Age>28</Age>
</Employee>
</Personnel>
=======内容结束========
目标是:输出如下内容
Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.
Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.
Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.
主要步骤
1,
Get a document builder using document builder factory and parse the xml
file to create a DOM object
Get a list of employee elements from the DOM
For each employee element get the id, name, age and type. Create an
employee value object and add it to the list.
At the end iterate through the list and print the employees to verify we
parsed it right.
a) 获取document builder
public void parseXmlFile(){
//get the factory
DocumentBuilderFactory dbf = DocumentBu
相关文档:
匹配特定数字:
^[1-9]d*$ //匹配正整数
^-[1-9]d*$ //匹配负整数
^-?[1-9]d*$ //匹配整数
^[1-9]d*|0$ //匹配非负整数(正整数 + 0)
^-[1-9]d*|0$ //匹配非正整数(负整数 + 0)
^[1-9]d*.d*|0.d*[1-9]d*$ //匹配正浮点数
^-([1-9]d*.d*|0.d*[1-9]d*)$ //匹配负浮点数
^-?([1-9]d*.d*| ......
11.写入属性
//import java.io.*;
File filereadonly=new File(%%1);
try {
boolean b=filereadonly.setReadOnly();
}
catch (Exception e) {
System.out.println("拒绝写访问:"+e.printStackTrace());
}
12.枚举一个文件夹中的所有文件
//import  ......
26.移动一个文件夹下所有文件到另一个目录
//import java.io.*;
File movefile=new File(%%1);
File[] movefiles=movefile.listFiles();
for(int i=0;i<movefiles.length;i++){
if(movefiles[i].isFile()){
int bytesum = 0;
int byteread  ......
39.写入XML数据库
//import java.io.*;
//import javax.xml.parsers.*;
//import org.xml.sax.*;
//import org.w3c.dom.*;
//import javax.xml.transform.*;
//import javax.xml.transform.dom.*;
//import javax.xml.transform.stream.*;
private Document ......