dom4j取2级、3级节点的值

xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<files>
    <file operate-type="add" file-type="doc">
        <id>1</id>
        <name>通知</name>
        <creator>张三</creator>
        <meta>
            <year>2010</year>
            <department>局机关</department>
        </meta>
    </file>
</files>


import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * @author codeif.com
 */
public class a {
	public static void main(String[] args) throws DocumentException {
		    SAXReader reader = new SAXReader();
		    Document doc = reader.read("d:\\files.xml");
	        Element root = doc.getRootElement();//根节点;
	   	    Element foo;
		    for (Iterator i = root.elementIterator("file"); i.hasNext();) {
			   foo = (Element) i.next();
			   System.out.println(" ID:" + foo.elementText("id"));
			   System.out.println(" Name:" + foo.elementText("name"));
			   System.out.println(" creator:" + foo.elementText("creator"));
			   //<meta>下的节点
                         String year= root.selectSingleNode("file/meta/year").getText();
                      String department = root.selectSingleNode("file/meta/department").getText();		    
				
		}
}

取<meta>下的节点的方法:
1、String year= root.selectSingleNode("file/meta/year").getText();

2、String year= root.element("files").element("file").element("meta").element("year").getTextTrim();

3、还可以用xpath


你可能感兴趣的:(java,xml)