Reputation: 79
Does anyone know of a neat way in java or any packages that will allow me to check if a Node in a DOM will match on a template in an xsl stylesheet.
For example;
<xsl:template match="elem/child/item">
...
</xsl:template>
Would be a template I'm looking for a match for using something like;
Node n = getNode();
String pattern = "elem/child/item"
boolean match = PatternMatcher.isMatch(n, pattern);
Of course where the pattern used could be any sort of XPath expression that could be used as a template match in an xsl stylesheet.
I would greatly appreciate it if anyone knows a nice way this could be acheived through packages etc. Thanks
Upvotes: 1
Views: 579
Reputation: 23248
Is Java's XPath API what you need?
InputSource source = new InputSource(new FileInputStream("myfile.xml"));
//Document source = ...; //or use a DOM document as the source
String expression = "//elem/child/item"; //XPath expression
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList matches = (NodeList)xPath.evaluate(expression, source, XPathConstants.NODESET);
System.out.println("Match count: " + matches.getLength());
Upvotes: 0
Reputation: 243449
Use:
//elem/child/item
this selects exactly all nodes in the XML document that are matched by the match pattern elem/child/item
.
To verify that a given node $n is matched by the template, use this XPath expression:
count($n | //elem/child/item) = count(//elem/child/item)
Alternatively (and this may be more efficient):
$n[self::item
and
parent::node()
[self::child
and
parent::node()
[self::elem]
]
]
Do note, the fact that a node is matched by a match-pattern doesn't mean that the template will be selected for processing this node (or that any template will be selected at all). Selection of template for processing depends on the existing <xsl:apply-templates>
, on whether there are other templates with higher import precedence or priority that also match the same node.
Upvotes: 0
Reputation: 163322
Saxon's XPathCompiler object:
http://www.saxonica.com/documentation/javadoc/net/sf/saxon/s9api/XPathCompiler.html
has a method compilePattern() that allows you to compile an XSLT Pattern. This is returned in the form of an XPathExecutable, which can be evaluated by (a) supplying the target node as the context node for evaluation, and (b) evaluating the expression to return a boolean which is true if the pattern matches the node or false otherwise.
Upvotes: 1
Reputation: 53694
Not super efficient, but you could simply run the xpath on the document and see if it returns the Node in question.
Upvotes: 1