Skip to Content.
Sympa Menu

xom-interest - Re: [XOM-interest] Query: Any way to determine ordering of two nodes?

xom-interest AT lists.ibiblio.org

Subject: XOM API for Processing XML with Java

List archive

Chronological Thread  
  • From: Wolfgang Hoschek <wolfgang.hoschek AT mac.com>
  • To: Gregory Garretson <gregory AT garretson.info>
  • Cc: xom-interest AT lists.ibiblio.org
  • Subject: Re: [XOM-interest] Query: Any way to determine ordering of two nodes?
  • Date: Mon, 13 Mar 2006 19:32:22 -0800

On Mar 13, 2006, at 6:05 PM, Gregory Garretson wrote:

Hello,

I've been using XOM for a few months now, and I really like it. I find
it useful, simple, and elegant. However, occasionally I come across
something I can't find an obvious way to do. Here's one:

Given two nodes in the same document, Is there a good way to determine
which of the nodes precedes the other in normal document order? Assuming
they are non-identical, of course. The API, FAQ, and tutorial haven't
given me any clues. I suspect you could do it with XPath, but there's
that restriction about query() only returning a nodeset.

I can think of very cumbersome ways of doing it, but I'm looking for
something that will be relatively efficient. Maybe I've missed something
obvious. Any suggestions would be very welcome.

Thanks,
Gregory Garretson


You could try the "<<" XPath 2.0 document order operator. Something like this:

import java.util.HashMap;
import java.util.Map;

import nu.xom.Node;
import nux.xom.pool.XQueryPool;
import nux.xom.xquery.XQuery;
import nux.xom.xquery.XQueryException;

public class OrderExample {

public static int compareTo(Node x, Node y) throws XQueryException {
if (x == y) return 0;
Map vars = new HashMap();
vars.put("x", x);
vars.put("x", y);
XQuery xquery = XQueryPool.GLOBAL_POOL.getXQuery("$x << $y",
null);
if (xquery.execute(null, null, vars).next().getValue().equals ("true")) {
return -1;
} else {
return 1;
}
}
}

The underlying comparison algorithm is in net.sf.saxon.xom.NodeWrapper.compareOrderFast().

Wolfgang.




Archive powered by MHonArc 2.6.24.

Top of Page