本帖最后由 nihao6154 于 2014-04-26 21:30:56 编辑

解决方案 »

  1.   

    如果不是必须用dom4j,我建议楼主用xpath解析
      第一层解析://pre:FieldArray
      第二层解析://pre:FieldArray/pre:FIELD/[position()=" + i+ "]/@GroupID";如果等于-1;一级,然后递归找子节点
      xpath语法我没测试,但是这样做肯定是能满足你的需求的
      

  2.   

        public static void main(String[] args) throws XPathExpressionException,
                ParserConfigurationException, SAXException, IOException
        {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);// never forget this!
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document doc = builder.parse("D:\\1.xml");
            // 先取根
            String itemStr = "//FieldArray/FIELD[@GroupID=-1]";
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(itemStr);
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 1; i <= nodes.getLength(); i++)
            {
                expr = xpath.compile("//FieldArray/FIELD[@GroupID=-1][position()="
                        + i + "]/@Index");
                Object index_id = expr.evaluate(doc, XPathConstants.STRING);
                System.out.println("我是父节点,id=" + index_id.toString());
                // 得到子节点
                getSon("//FieldArray/FIELD[@GroupID=" + index_id.toString() + "]",
                        doc, xpath);
            }
        }    public static void getSon(String url, Document doc, XPath xpath)
                throws XPathExpressionException
        {
            XPathExpression expr = xpath.compile(url);
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
            for (int i = 1; i <= nodes.getLength(); i++)
            {
                System.out.println(url + "[position()=" + i + "]/@Index");
                expr = xpath.compile(url + "[position()=" + i + "]/@Index");
                Object index_id = expr.evaluate(doc, XPathConstants.STRING);
                System.out.println("我是子节点,index_id=" + index_id.toString());
                // 得到子节点
                getSon("//FieldArray/FIELD[@GroupID=" + index_id.toString() + "]",
                        doc, xpath);
            }
        }
      

  3.   

    还有我想问下,如果用xpath解析的话,是要导入saxpath.jar就可以吧,还需要其他的jar包吗?
      

  4.   

    还有节点里的属性用xpath怎么取?
      

  5.   

    都打成jar包了,我也没仔细看,那个demo我测试了应该是体现级别的,我用的都是很基础的xpatch语法,网上很好找