XML是一种可扩展置标语言,又称可扩展的编辑语言。XML文档的定义格式有两种:DTD和Schema格式,由于Schema是xml本身的,所以应用的非常普遍。xml的作用是文件的读写,所以在web开发中也得到了广泛应用,作为一种配置文件,充分发挥了它读写的功能。XML的解析方式有四种:DOM,SAX,JDOM,DOM4J。DOM是一种标准模型,也是W3C所推荐的。几种解析方式各有优缺点,但是DOM4J几种了前几种的有点,在web开发中得到广泛应用,本人也推荐掌握DOM4J。四种解析方式至少掌握一种即可,如果自己有时间精力最好全部掌握。下面是以DOM4J进行文件的读写实例:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4j {
public static void main(String[] args) {
File file=new File("src/XML/gg.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
write(file);
read(file);
}
//XML的写入
private static void write(File file) {
// 创建document文档
Document doc=DocumentHelper.createDocument();//得到document文件
//添加元素
Element e=doc.addElement("root");//添加根元素
Element student=e.addElement("student");//添加子元素
Element name=student.addElement("name");
Element age=student.addElement("age");
Element num=student.addElement("num");
Element hight=student.addElement("hight");
//给元素赋值
student.addAttribute("id", "001");
student.addAttribute("class", "201班");
name.addText("lisi");
age.addText("12");
//把document保存到文件中
//无格式化输出
/* try {
FileWriter fw=new FileWriter(file);
doc.write(fw);
fw.flush();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
*/
//格式化输出
try {
FileWriter fw=new FileWriter(file);
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
format.setIndent(" ");
XMLWriter xw=new XMLWriter(fw,format);
xw.write(doc);
fw.flush();
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//XML的解析
private static void read(File file) {
SAXReader reader=new SAXReader();
try {
Document doc=reader.read(file);
Element root=doc.getRootElement();
List list=root.elements("student");
for(int i=0;i<list.size();i++){
Element e=(Element)list.get(i);
System.out.println(e.attributeValue("id")+" "+
e.attributeValue("class")+" "+
e.elementText("name")+" "+
e.elementText("age")+" "+
e.elementText("num")+" "+
e.elementText("hight"));
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}