假设我有一个XML是这样结构的:
<item id=A>
    <title>aaa</title>
    <item id=AA>
       <title></title> 
       <item><title></title></item>
    </item >
    <item id=Aa>
       <title></title>         
    </itemAa>
</itemA>
<item id=B>
    <title>bbb</title>
    <item>
       <title></title>         
    </item>
    <item>
       <title></title>         
    </item>
</itemB>
我想只获取item id=A下面的item子节点<item id=AA>、<item id=Aa>这两个节点,不要连<item id=AA>的item节点也返回!

解决方案 »

  1.   

    那就采用SAX技术吧,DOM是把整个XML文档装载,麻烦
      

  2.   


    public String getLocationURL(HttpServletRequest req,String file,String item) {
    String filepath = req.getRealPath("WEB-INF/classes/com/feecc/util/sql")+"/"+file;
    String sql = "" ;

    try {
    Element el = this.getNodeByPath(filepath, item);
    Node node = el.getFirstChild();
    sql = node.getNodeValue() ;

    if("".equals(sql) || sql == null) {
    throw new Exception("xml没有配置sqlpath:"+sql);
    }
    } catch (Exception e) {
    e.printStackTrace();
    }

    return sql ;
    }

    private Element getNodeByPath(String configfile,String item) throws Exception{
    Document doc = this.getXml(configfile);
    Element els = (Element)doc.getDocumentElement();

    NodeList nl = els.getChildNodes();
    for(int j=0;j<nl.getLength();j++){
    if(item.equals(nl.item(j).getNodeName())){
    els = (Element) nl.item(j);
    break;
    }
    }
    return els;

    }

    private Document getXml(String configFileName) throws Exception {
    try {
    DocumentBuilderFactory factory = DocumentBuilderFactory
    .newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(configFileName);
    doc.normalize();
    return doc;
    } catch (Exception e) {
    throw new Exception("get xml file error-->"+e.getMessage(),e.getCause());
    }
    }
      

  3.   

    靠,这么麻烦,只用dom4j取过全部的,没这么多要求过!
      

  4.   

    辛苦拉!~~因为我的XML是从具体路径随机选的!~感觉用标准dom做太麻烦了!~~所以小弟改用DOM4J了!~~~你这样太麻烦了!~~这个例子还是我简化过的!~~