今天了解了一下dom4j对xml的读写,保存一下代码以防以后忘记
读取xml:
private static Document getDocument(String xmlUrl)
throws DocumentException, FileNotFoundException {
SAXReader reader = new SAXReader();
// 从文件中获取document
Document document = reader.read(new FileInputStream(xmlUrl));
return document;
}
public static void parseXml(String xmlUrl) throws Exception {
Document document = getDocument(xmlUrl);
// 获取根节点
Element root = document.getRootElement();
// 获取root下的所有子节点
System.out.println(root.getName());
Iterator<Element> it = root.elementIterator();
iteratorChildNode(it);
}
private static void iteratorChildNode(Iterator<Element> it) {
while (it.hasNext()) {
Element ele = it.next();
System.out.println(ele.getName());
Iterator<Element> iter = ele.elementIterator();
iteratorChildNode(iter);
}
}
使用dom4j生成一个xml代码如下:
public static void generateDocument() throws Exception {
Document document = DocumentHelper.createDocument();
//创建一个根节点
Element element = document.addElement("Students");
//在根节点下面加一个注释
element.addComment("学生信息!");
//生成子节点
Element stuElement = element.addElement("Student");
//给该节点添加一些属性
stuElement.addAttribute("id", "1001");
Element nameElement = stuElement.addElement("name");
nameElement.addText("李岩");
Element ageElement = stuElement.addElement("age");
ageElement.addText("22");
Element sexElement = stuElement.addElement("sex");
sexElement.addText("男");
//使用输出流将xml输出到指定的地址下
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File(
"src/xml/student.xml")));
xmlWriter.write(document);
xmlWriter.close();
}