利用dom4j解析XML文档
导入dom4j.jar包
2.创建XML文件books.xml
THIS IS TITLE[1] AUTHOR[1] THIS IS TITLE[2] AUTHOR[2]
3.可以利用Java代码创建XML文档
package per.lx.test;import java.io.File;import java.io.FileOutputStream;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class DemoCreate { public static void main(String[] args) throws Exception { Document doc = DocumentHelper.createDocument(); //生成根节点 Element books = doc.addElement("books"); //注意这里Element的对象的方法是用父节点调用addElement方法,生成子节点 Element book1 = books.addElement("book"); Element title1 = book1.addElement("title"); Element author1 = book1.addElement("author"); Element book2 = books.addElement("book"); Element title2 = book2.addElement("title"); Element author2 = book2.addElement("author"); book1.addAttribute("id", "001"); title1.setText("THIS IS TITLE[1]"); author1.setText("AUTHOR[1]"); book2.addAttribute("id", "002"); title2.setText("THIS IS TITLE[2]"); author2.setText("AUTHOR[2]"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); File file = new File("D:"+File.separator+"books.xml"); XMLWriter writer = new XMLWriter(new FileOutputStream(file),format); writer.write(doc); }}
4.利用java代码获取,解析XML内容
package per.lx.test;import java.io.File;import java.util.List;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;public class DemoRead { public static void main(String[] args) throws Exception { SAXReader reader = new SAXReader(); File file = new File("D:/books.xml"); Document document = reader.read(file); Element root = document.getRootElement(); ListchildElements = root.elements(); for (Element child : childElements) { //这是不知道节点名字的情况下,知道节点名字参见PS List attributeList = child.attributes(); for (Attribute attr : attributeList) { System.out.println(attr.getName() + ": " + attr.getValue()); } System.out.println("-----上面是得到ID-----"); List elementList = child.elements(); for (Element ele : elementList) { System.out.println(ele.getName() + ": " + ele.getText()); } System.out.println("-----上面是得到数据-----"); } }}
PS:上面获取是在不知道节点名字的情况下进行获取
ListchildElements = root.elements(); for (Element child : childElements) { //获取book标签属性的值用attributeValue System.out.println("id:"+child.attributeValue("id")); //获取便签的Text用elementText System.out.println("title:" + child.elementText("title")); System.out.println("author:" + child.elementText("author")); System.out.println(); }
以上只是对解析出来的结果进行一个输出,知道节点为id,title和author的情况下可以用此方法