使用dom4j读XML文件
package XMLlearning;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.util.Iterator;
/**
* Created by junk beat on 2019/2/23.
*/
public class ParserXML {
public static void main(String[] args){
SAXReader reader = new SAXReader();
try {
Document document = reader.read("src//XMLlearning//newFile.xml");
Element root = document.getRootElement(); //得到根元素
//System.out.println(root.getName());
//Element 类
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());
}
System.out.println(ele.getName());
//Attribute类
Iterator<Attribute> attributes = ele.attributeIterator();
while(attributes.hasNext()){
Attribute ab = attributes.next();
System.out.println(ab.getName() + ", " + ab.getValue());
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
使用dom4j写XML文件
package XMLlearning;
import org.dom4j.*;
import java.io.FileWriter;
/**
* Created by junk beat on 2019/2/23.
*/
public class createXML {
public static void main(String[] args) throws Exception{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root"); //添加根节点,并返回其引用
Element author1 = root.addElement("author")
.addAttribute("name", "James")
.addAttribute("location", "UK")
.addText("James Strachan");
author1.addElement("salary").addText("10000");
Element author2 = root.addElement("author")
.addAttribute("name", "Bob")
.addAttribute("location", "US")
.addText("Bob McWhirter");
FileWriter out = new FileWriter("src//XMLlearning//writer.xml");
document.write(out);
out.close();
}
}
PS:jvm默认项目的根目录为根目录