##Basic Overview
is a JavaXML API , similar to jdom, used to read and write XML files. dom4j is a very excellent JavaXML API, which has the characteristics of excellent performance, powerful functions and extremely easy to use. It is also a Open source software, you can find it at SourceForge. You can also find an article on IBM developerWorks on the performance, functionality and ease of use of the mainstream Java XML API reviews, so you can know that dom4j is excellent in every aspect. Nowadays you can see that more and more Java software are using dom4j to read and write XML, it is particularly worth mentioning that even Sun#JAXM is also using dom4j . This is already a must-use jar package, Hibernate also uses it to read and write configuration files.
PS:DOM4JOne of the reasons why it is so powerful is that it supports XPath Technology, DOM4J also has corresponding reference documents, you can search and download them if you need them.
Why is thereDOM and SAX technology, the disadvantage of the former is that it is time consuming Memory, the disadvantage of the latter is that it can only perform read operations, while DOM4J can both submit efficiency and perform crud operations .
PS: To use DOM4J, you need to import the corresponding basic JAR package, If you use the extension function of DOM4J, you also need to import the extension JAR package.
SAXReader reader = new SAXReader(); Document document = reader.read(new File(“src/input.xml"));
String text = "<members></members>"; Document document = DocumentHelper.parseText(text);
Document document = DocumentHelper.createDocument(); //创建根节点 Element root = document.addElement("members");
PS: Be careful to import the corresponding JAR package.
Element root = document.getRootElement();
Element element=node.element(“书名");
String text1=node.getText(); String text2=node.getTextTrim(); // 去掉内容前面和后面的空格
List nodes = rootElm.elements("member"); for (Iterator it = nodes.iterator(); it.hasNext();) { Element elm = (Element) it.next(); // do something }
for(Iterator it=root.elementIterator();it.hasNext();){ Element element = (Element) it.next(); // do something }
Element ageElm = newMemberElm.addElement("age");
element.setText("29");
//childElm是待删除的节点,parentElm是其父节点 parentElm.remove(childElm);
Element contentElm = infoElm.addElement("content"); contentElm.addCDATA(diary.getContent());
PS: Note that nodes cannot be accessed across layers.
Element root=document.getRootElement(); //属性名name Attribute attribute=root.attribute("size");
String text=attribute.getText();
Attribute attribute=root.attribute("size"); root.remove(attribute);
Element root=document.getRootElement(); for(Iterator it=root.attributeIterator();it.hasNext();){ Attribute attribute = (Attribute) it.next(); String text=attribute.getText(); System.out.println(text); }
newMemberElm.addAttribute("name", "sitinspring");
Attribute attribute=root.attribute("name"); attribute.setText("sitinspring");
1.Get the node list at the insertion position (list)
2.Call list.add(index,elemnent), determined by index## The insertion position of #element.
ElementElements can be obtained through the DocumentHelper object. Sample code:
Element aaa = DocumentHelper.createElement("aaa"); aaa.setText("aaa"); List list = root.element("书").elements(); list.add(1, aaa); //更新document
XMLWriter writer = new XMLWriter(new FileWriter("output.xml")); writer.write(document); writer.close();
OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("utf-8"); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("src/com/pc/XML8.xml"), outputFormat); xmlWriter.write(document); xmlWriter.close();
PS:出现乱码的原因是因为输出字符集不能识别中文,这样可以通过OutputFormat的setEncoding方法设置为”UTF-8”,然后再使用XMLWriter这种形参的(OutputStream out, OutputFormat format) 构造方构造方法,就能解决乱码问题了,至于为什么会用createPrettyPrint方法,是因为这样做输出的格式更符合人的阅读习惯。
XML8.xml
<?xml version="1.0" encoding="utf-8"?> <班级 班次="1班" 编号="C1"> <学生 学号="n1" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1"> <名字>张三</名字> <年龄>20</年龄> <介绍>不错</介绍> </学生> <学生 学号="n2" 性别="女" 授课方式="面授" 朋友="n1 n3" 班级编号="C1"> <名字>李四</名字> <年龄>18</年龄> <介绍>很好</介绍> </学生> <学生 学号="n3" 性别="男" 授课方式="面授" 朋友="n2" 班级编号="C1"> <名字>王五</名字> <年龄>22</年龄> <介绍>非常好</介绍> </学生> <学生 性别="男" 班级编号="C1"> <名字>小明</名字> <年龄>30</年龄> <介绍>好</介绍> </学生> </班级>
package com.pc; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; 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; /** * * @author Switch * @function 使用DOM4j解析XML文件 * */ public class XML8 { // 使用DOM4j对XML进行CRUD操作 public static void main(String[] args) throws Exception { // 1.得到解析器 SAXReader saxReader = new SAXReader(); // 2.指定解析哪个XML文件 Document document = saxReader.read(new File("src/com/pc/XML8.xml")); // list(document.getRootElement()); // read(document); // readByXPath(document); // add(document); // delete(document); // updateElement(document); // updateAttribute(document); // addByIndex(document, 3); } // 更新属性(修改所有班级编号为C2) public static void updateAttribute(Document document) throws Exception { // 得到所有学生 List<Element> students = document.getRootElement().elements("学生"); for (Element e : students) { // 修改班级编号 e.addAttribute("班级编号", "C2"); } updateToXML(document); } // 更新元素(将所有学生的年龄+3) public static void updateElement(Document document) throws Exception { // 得到所有学生 List<Element> students = document.getRootElement().elements("学生"); for (Element e : students) { // 取出年龄 Element age = e.element("年龄"); age.setText(Integer.parseInt(age.getTextTrim()) + 3 + ""); } updateToXML(document); } // 删除元素(删除第一个学生) public static void delete(Document document) throws Exception { // 找到元素 Element stu = document.getRootElement().element("学生"); // 删除 stu.getParent().remove(stu); // 更新 updateToXML(document); } // 添加元素到指定位置 public static void addByIndex(Document document, int index) throws Exception { // 创建一个元素 Element newStu = DocumentHelper.createElement("学生"); newStu.setText("小花"); // 得到所有学生的list List<Element> students = document.getRootElement().elements("学生"); // 按索引添加 students.add(index, newStu); // 更新 updateToXML(document); } // 添加元素(添加一个学生到xml中) public static void add(Document document) throws Exception { // 创建一个学生节点对象 Element newStu = DocumentHelper.createElement("学生"); // 给元素添加属性 newStu.addAttribute("学号", "n4"); Element newStuName = DocumentHelper.createElement("名字"); Element newStuAge = DocumentHelper.createElement("年龄"); Element newStuIntro = DocumentHelper.createElement("介绍"); // 把子元素挂载到学生节点下 newStu.add(newStuName); newStu.add(newStuAge); newStu.add(newStuIntro); // 将学生挂载在根节点下 document.getRootElement().add(newStu); // 更新 updateToXML(document); } private static void updateToXML(Document document) throws UnsupportedEncodingException, FileNotFoundException, IOException { // 更新xml文件 // 直接输出会出现中文乱码 OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("utf-8"); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream( "src/com/pc/XML8.xml"), outputFormat); xmlWriter.write(document); xmlWriter.close(); } // xpath技术,跨层读取某个元素 public static void readByXPath(Document document) throws Exception { // 取出第一个学生 Element student = (Element) document.selectSingleNode("/班级/学生[1]"); System.out.println("姓名:" + student.elementText("名字") + "\t年龄:" + student.elementText("年龄") + "\t介绍:" + student.elementText("介绍") + "\t性别:" + student.attributeValue("性别")); } // 读取指定的某个元素(读取第一个学生的信息) public static void read(Document document) throws Exception { // 得到根元素 Element root = document.getRootElement(); // root.elements("学生"); 取出root元素下的所有学生元素 // root.element("学生"); 取出root元素下的第一个学生元素 // 取出root元素下的第一个学生元素 Element student = (Element) root.elements("学生").get(0); System.out.println("姓名:" + student.elementText("名字") + "\t年龄:" + student.elementText("年龄") + "\t介绍:" + student.elementText("介绍") + "\t性别:" + student.attributeValue("性别")); } // 遍历xml文件 public static void list(Element element) { System.out.println("元素名称:" + element.getName() + "\t元素内容:" + element.getTextTrim()); Iterator<Element> iterator = element.elementIterator(); while (iterator.hasNext()) { Element e = iterator.next(); // 递归 list(e); } } }
以上就是XML编程-DOM4J的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)!