dom4j对xml的操作
解析xml文件
dom4j就是个解析xml文件的的东西。
可以用 dom4j 可以从github上下载:https://dom4j.github.io
一下给出代码示例:
import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.util.Iterator; public class Main { public static void main(String[] args) throws Exception { SAXReader reader = new SAXReader(); Document document = reader.read("xmlFolder/xmlTest01.xml"); Element root = document.getRootElement(); System.out.println("父节点:" + root.getName());//输出父节点名字 Iterator<Element> it = root.elementIterator(); while (it.hasNext())//遍历子节点 { Element ele = it.next(); if (ele.getName().equals("good")) { Element name = ele.element("name");//获取"name"节点的内容 if (name != null) System.out.println(name.getText());//输出节点的text内容 } System.out.println(ele.getName());//输出子节点名字 Iterator<Attribute> attributes = ele.attributeIterator(); while (attributes.hasNext()) { Attribute ab = attributes.next(); //属性名 : 属性值 System.out.println(ab.getName() + ":" + ab.getValue()); } } } }
创建xml文件
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import java.io.FileWriter; public class Main { public static void main(String[] args) throws Exception { Document document = DocumentHelper.createDocument(); Element root = document.addElement("root"); root.addElement("author")//元素名 .addAttribute("name", "James")//属性名, 属性值 .addAttribute("location", "UK")//属性名, 属性值 .addText("James Strachan");//元素内容 root.addElement("author") .addAttribute("name", "Bob") .addAttribute("location", "US") .addText("Bob McWhirter"); FileWriter out = new FileWriter("foo.xml"); document.write(out); out.close(); } }
浙公网安备 33010602011771号