我用 jdom + xPath 解析下面的 sample.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>     
<HD>     
 <disk name="C">     
  <capacity>8G</capacity>     
  <directories>200</directories>     
  <files>1580</files>     
 </disk>     
 <disk name="D">       
  <capacity>10G</capacity>     
  <directories>500</directories>     
  <files>3000</files>       
 </disk>     
 <disk name="E">       
  <capacity>20G</capacity>     
  <directories>800</directories>     
  <files>10000</files>       
 </disk>  
</HD>
java代码:
public class Test {   
    private Document doc;   
  
    public Test(String file) throws Exception {   
        SAXBuilder sb = new SAXBuilder();   
        doc = sb.build(file);   
    }   
  
    private Element getRootElement() {   
        return doc.getRootElement();   
    }   
  
    public String getValue(Element element, String xPath) throws Exception {   
        return ((Text) XPath.selectSingleNode(element, xPath)).getTextNormalize();   
    }   
  
    public List<Element> getList(String xPath) throws Exception {   
        List<Element> result = new ArrayList<Element>();   
  
        List list = XPath.selectNodes(getRootElement(), xPath);   
        for(Object o : list) result.add((Element) o);   
  
        return result;   
    }   
  
    public static void main(String[] args) throws Exception {   
        String file = "sample.xml";   
        Test test = new Test(file);   
  
        List<Element> list = test.getList("/HD/disk");   
        for(Element e : list) {   
            System.out.println("name : " + e.getAttributeValue("name"));   
            System.out.println("capacity : " + test.getValue(e, "capacity/text()"));   
            System.out.println("disk C capacity : " + test.getValue(e, "//disk[@name='C']/capacity/text()"));   
            System.out.println("--------------");   
        }   
    }   
}
输出结果:name : C   
capacity : 8G   
disk C capacity : 8G   
--------------   
name : D   
capacity : 10G   
disk C capacity : 8G   
--------------   
name : E   
capacity : 20G   
disk C capacity : 8G   
--------------  
为什么下面这一行没有问题呢?System.out.println("disk C capacity : " + test.getValue(e, "//disk[@name='C']/capacity/text()")); 为什么在 name 为 D 和 E 时还能够访问到 disk C 的属性值呢??? 

解决方案 »

  1.   

    给你一个例子吧!
    前几天刚用过这个:<?xml version="1.0" encoding="UTF-8"?>
    <dataSource>
    <hostAddress>192.168.134.64</hostAddress>
    <databaseName>dbname</databaseName>
    <userName>sa</userName>
    <password>123</password>
    </dataSource>
    解析代码:public static HashMap getDataSource(String dataSourcePath){
    // String dataSourcePath="c:/param/dataSource_RecordDB.xml";
    HashMap dataSource=new HashMap();
    SAXReader saxReader = new SAXReader();
     try {
    Document document = saxReader.read(new File(dataSourcePath));

    Node _hostAddress=document.selectSingleNode("/dataSource/hostAddress");
    Node _databaseName=document.selectSingleNode("/dataSource/databaseName");
    Node _userName=document.selectSingleNode("/dataSource/userName");
    Node _password=document.selectSingleNode("/dataSource/password");

    dataSource.put("hostAddress",_hostAddress.getText());
    dataSource.put("databaseName", _databaseName.getText());
    dataSource.put("userName",_userName.getText());
    dataSource.put("password",_password.getText());

    } catch (DocumentException e) {
    e.printStackTrace();
    }
    return dataSource;
    }
      

  2.   

    import java.io.File;
    import java.io.IOException;
    import java.util.List;import org.jdom.Attribute;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;
    public class Test1 {
    private String outString="";
    public Test1(String xmlPath){
    SAXBuilder sb=new SAXBuilder();
    Document doc=null;
    try {
    doc=sb.build(Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlPath));
    } catch (JDOMException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    Element rootElem=doc.getRootElement();
    PrintContent(rootElem);
    }
    private void PrintContent(Element elem){
    List list=elem.getChildren();
    for (Object e : list) {
    Element el=(Element)e;
    PrintContent(el);
    }
    if(!elem.getAttributes().isEmpty()){
    outString+=elem.getName()+":"+((Attribute)elem.getAttributes().get(0)).getValue()+"\n";
    }
    if(elem.getChildren().isEmpty()){
    outString+=elem.getName()+":"+elem.getValue()+"\n";
    }
    }
    public String getString(){
    return outString;
    }
    public static void main(String[] args){
    Test1 test=new Test1("NewFile1.xml");
    System.out.println(test.getString());
    }
    }
      

  3.   

    import java.io.File;
    import java.io.IOException;
    import java.util.List;import org.jdom.Attribute;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.JDOMException;
    import org.jdom.input.SAXBuilder;public class Test1 {
            private String outString = "";        public Test1(String xmlPath) {
                    SAXBuilder sb = new SAXBuilder();
                    Document doc = null;
                    try {
                            doc = sb.build(Thread.currentThread().getContextClassLoader()
                                            .getResourceAsStream(xmlPath));
                    } catch (JDOMException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }                catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                    }
                    Element rootElem = doc.getRootElement();
                    PrintContent(rootElem);
            }        private void PrintContent(Element elem) {
                    List list = elem.getChildren();
                    for (Object e : list) {
                            Element el = (Element) e;
                            PrintContent(el);
                    }
                    if (!elem.getAttributes().isEmpty()) {
                            outString += elem.getName() + ":"
                                            + ((Attribute) elem.getAttributes().get(0)).getValue()
                                            + "\n";
                    }
                    if (elem.getChildren().isEmpty()) {
                            outString += elem.getName() + ":" + elem.getValue() + "\n";
                    }
            }        public String getString() {
                    return outString;
            }        public static void main(String[] args) {
                    Test1 test = new Test1("NewFile1.xml");
                    System.out.println(test.getString());
            }
    }