打印本文 打印本文 关闭窗口 关闭窗口
XPath中如何比较不同类型的对象
作者:武汉SEO闵涛  文章来源:敏韬网  点击数1511  更新时间:2009/4/23 10:51:18  文章录入:mintao  责任编辑:mintao
目前XPath2.0还没有正式定稿,因此本文的讨论是基于XPath1.0.
XPath支持四种基本类型:
1. Node-set
2. string
3. number
4. boolean
我们知道一个Location Step由Axis,Node Test和Predicate三部分组成,而用于查询XML文档的XPath又是由若干Location Step组成,比如/table/row[id=''''0000'''']。在Predicate中几乎总是需要运用=,!=,<,<=,<=进行比较。而对于不同的对象如何进行比较,尤其是涉及到node-set的比较却是十分容易使人困惑。比如对下面文档进行Root/Numbers[Integer/@value > 4]<Root>查询。
<Numbers>
<Integer value="4" />
<Integer value="2" />
<Integer value="3" />
</Numbers>
<Numbers>
<Integer value="2" />
<Integer value="3" />
<Integer value="6" />
</Numbers>
</Root>

下面我以伪代码的形式解释XPath中是如何比较不同对象的。其中compareObjects涉及到

boolean compareObjects(Object operand1,Object operand2,String operator)throws Exception{

        //both objects to be compared are node-sets

        if(both operand1 and operand2 are node-sets){

            Iterator i1 = operand1.iterator();

            Iterator i2 = operand2.iterator();

            while((node1 =i1.next()!=null){

                while((node2 =i2.next()!=null){

                    //convert node1 and node2 to string values

                    String s1 = (String)node1;

                    String s2 = (String)node2;

                    if(compareBasic(s1,s2,operator))return true;

                }

            }

        //neither object to be compared is a node-set

        }else if(neither operand1 nor operand2 is node-set){

             return compareBasic(operand1,operand2,operator);

        }else{

        //In this case, one object is node-set and the other is of basic type.Assume operand1 is node-set

            Iterator i1 = operand1.iterator();

            while((node1 =i1.next()!=null)

[1] [2] [3]  下一页

打印本文 打印本文 关闭窗口 关闭窗口