标签:dom4j
1.加载XML文档
2.获得根元素
3.取得某节点的单个子节点
4.取得节点的文字
5.取得某节点下名为"book"的所有字节点并进行遍历
7.设置节点文字.
8.删除某节点.
属性相关.
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文件. 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.将字符串转化为XML String text = "<members> <member>sitinspring</member> </members>"; 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"?> <projectDescription> <name>MemberManagement</name> <comment></comment> <projects> <project>PRJ1</project> <project>PRJ2</project> <project>PRJ3</project> <project>PRJ4</project> </projects> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription>
使用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(); } } |
标签:dom4j
原文地址:http://blog.csdn.net/xiaokui_wingfly/article/details/17167959