dom4j 中selectNodes选取节点排序问题

问题描述:

      在dom4j中可以通过xpath过滤xml数据中的节点,并且可以进行排序。调用方法有两种:

     

      方法一:org.dom4j.XPath   

      selectNodes(Object context, XPath sortXPath)
           selectNodes evaluates the XPath expression on the given Nodeor Listof Nodes and returns the result as a List of Node s sorted by the sort XPath expression.

   

      方法二:org.dom4j.Node

      selectNodes(String xpathExpression, String comparisonXPathExpression)
           selectNodes evaluates an XPath expression then sorts the results using a secondary XPath expression Returns a sorted List of Node instances.

 

解决方法:

      扩展DefaultXPath自己实现了一个NumberXPath类,源码如下:

      

package org.dom4j.xpath;

import org.dom4j.Node;

public class NumberXPath extends DefaultXPath{
    public NumberXPath(String text){
        super(text);
    }
    protected Object getCompareNumberValue(Node node) {
        return numberValueOf(node);
    }
}

    调用方法:

   

String srcXML = "...xml文字...";   //参见xml文件
Document doc = DocumentHelper.parseText(srcXML);
List list = doc.selectNodes("doc/person/adds/add[@ID]");

org.dom4j.XPath path =new NumberXPath("@ID");
path.sort(list);

//查看结果
Iterator i1 = list.iterator();
while(i1.hasNext()){
    Element element = (Element) i1.next();
    System.out.println(element.attributeValue("ID"));
}

 

   XML文件:

   

<?xml version="1.0" encoding="GBK"?>
<doc>
    <person>
        <name>某人</name>
        <adds>            
            <add ID="01">
                <BS>10002</BS>
                <note>西安市太白路</note>
            </add>
            <add ID="02">
                <BS>10002</BS>
                <note>空ID节点啊</note>
            </add>
            <add ID="12">
                <BS>10002</BS>
                <note>空ID节点啊</note>
            </add>
            <add>
	<BS xmlns="10001"/>
                <note>西安市太白路2</note>
            </add>
         </adds>
    </person>
</doc>

  

你可能感兴趣的:(xml)