javaXML文件的编写与读取
XML文件的读取
读写xml文件需要配置 dom4j.jar
。
import java.io.File;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XMLParseDemo {
/**
*
* @author blue
* @throws DocumentException
*
* @date 2020年8月13日
*
*/
public static void main(String[] args) throws DocumentException {
// 1.创建SAXReader对象
SAXReader reader = new SAXReader();
File file = new File("src\\Student.xml");
// 2.读文件
Document document =reader.read(file);
// 3.获取根节点
Element root = document.getRootElement();
// 4.获取子节点
List<Element> childElements = root.elements();
// 遍历子节点
for (Element child : childElements) {
System.out.println("\t" + child.getName() + "\t");
List<Attribute> attrs = child.attributes();
for (Attribute attr : attrs) {
System.out.println(attr.getName() + ":" + attr.getValue() + "\t");
}
// 获取子元素
System.out.println();
List<Element> elementList = child.elements();
for (Element element : elementList) {
System.out.println("\t\t"+element.getName() + "\t" + element.getText() + "\r\n");
}
System.out.println();
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class WriterXML {
/**
*
* @author blue java程序写出一个XML文档
* @throws FileNotFoundException
* @throws Exception
* @date 2020年8月14日
*
*/
public static void main(String[] args) throws Exception {
// 定义Document对象
Document document = DocumentHelper.createDocument();
// 定义根节点
Element root = document.addElement("books");// 创建根节点
// 子节点
Element book = root.addElement("book");
Element title = book.addElement("title");
Element author = book.addElement("author");
// 节点添加属性
book.addAttribute("id", "001");
// 节点添加文本
title.setText("哈利波特");
author.setText("JK罗琳");
// 子节点2
Element book1 = root.addElement("book");
Element title1 = book1.addElement("title");
Element author1 = book1.addElement("author");
// 节点添加属性
book1.addAttribute("id", "002");
// 节点添加文本
title1.setText("茶花女");
author1.setText("小仲马");
//实例化输出格式对象
OutputFormat format=OutputFormat.createPrettyPrint();
//设置编码
format.setEncoding("utf-8");
//创建文件 File.separator自动分割符
File file =new File("E:"+File.separator+"books.xml");
//创建写对象
XMLWriter writer=new XMLWriter(new FileOutputStream(file),format);
writer.write(document);
writer.close();
}
}