1、加载XML文档SAXReader reader = new SAXReader();
Document doc = reader.read("src/book.xml");
2、获得根元素Node root = doc.getRootElement();
或
Element r = doc.getRootElement();
3、取得某节点的单个子节点Element root = root.getRootElement();
Element memberElm=root.element("member");// "member"是节点名
4、取得节点的文字String text=memberElm.getText();
5、取得某节点下名为"book"的所有字节点并进行遍历Element r = doc.getRootElement();
List titles = r.elements("book");
for(int i=0;i
System.out.println(((Element)titles.get(i)).asXML());
}
6、在某节点下添加子节点Element ageElm = newMemberElm.addElement("age");
7、设置节点文字ageElm.setText("29");
8、删除某节点parentElm.remove(childElm);// childElm是待删除的节点,parentElm是其父节点
属性相关
1、取得某节点下的某属性Element root=document.getRootElement();
Attribute attribute=root.attribute("size");// 属性名name
2、取得属性的文字String text=attribute.getText();
也可以用:
String text2=root.element("name").attributeValue("firstname");这个是取得根节点下name字节点的属性firstname的值.
3、遍历某节点的所有属性Element root = document.getRootElement();
for (Iterator it = root.attributeIterator(); it.hasNext();) {
Attribute attribute = (Attribute) it.next();
String text = attribute.getText();
System.out.println(text);
}
4、设置某节点的属性和文字newMemberElm.addAttribute("name", "sitinspring");
5、设置属性的文字Attribute attribute=root.attribute("name");
attribute.setText("sitinspring");
6、删除某属性Attribute attribute = root.attribute("size");// 属性名name
root.remove(attribute);
将文档写入XML文件
1、文档中全为英文,不设置编码,直接写入的形式XMLWriter writer = new XMLWriter(new FileWriter("output.xml"));
writer.write(document);
writer.close();
2、文档中含有中文,设置编码格式写入的形式OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK"); // 指定XML编码
XMLWriter writer = new XMLWriter(new FileWriter("output.xml"), format);
writer.write(document);
writer.close();
字符串与XML的转换
1、将字符串转化为XMLString text = " sitinspring ";
Document document = DocumentHelper.parseText(text);
2、将文档或节点的XML转化为字符串SAXReader reader = new SAXReader();
Document document = reader.read(new File("input.xml"));
Element root = document.getRootElement();
String docXmlText = document.asXML();
String rootXmlText = root.asXML();
Element memberElm = root.element("member");
String memberXmlText = memberElm.asXML();
使用XPath快速找到节点. 读取的XML文档示例<?xml version="1.0" encoding="UTF-8"?>
MemberManagement
PRJ1
PRJ2
PRJ3
PRJ4
org.eclipse.jdt.core.javabuilder
org.eclipse.jdt.core.javanature
使用XPath快速找到节点project.public static void main(String[] args) {
SAXReader reader = new SAXReader();
try {
Document doc = reader.read(new File("sample.xml"));
List projects = doc.selectNodes("/projectDescription/projects/project");
Iterator it = projects.iterator();
while (it.hasNext()) {
Element elm = (Element) it.next();
System.out.println(elm.getText());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}