Given a list of xpath statements, I want to write a stylesheet that will run through an xml document and output the same document but with a comment inserted before the node identified in each xpath statement. Let's make up an example. Start with an xml instance holding the xpath statements:
<paths>
<xpath location="/root/a" annotate="1"/>
<xpath location="/root/a/b" annotate="2"/>
</paths>
Given the input:
<root>
<a>
<b>B</b>
</a>
<c>C</c>
</root>
It should produce:
<root>
<!-- 1 -->
<a>
<!-- 2 -->
<b>B</b>
</a>
<c>C</c>
</root>
My initial thought is to have an identity stylesheet which takes a file-list
param, calls the document
function on it to get the list of xpath nodes. It would then check each node of the input against that list and then insert the comment node when it finds one, but I expect that might be highly inefficient as the list of xpaths gets large (or maybe not, tell me. I'm using saxon 9).
So my question: Is there an efficient way to do something like this?
I'm not sure if kjhughes' suggestion of creating a second transform would be more efficient than your original idea or not. I do see the possibility of that second transform becoming huge if your
paths
XML gets large.Here's how I'd do it...
XML Input
"paths" XML (paths.xml)
XSLT 2.0
XML Output
Overview:
Write a meta XSLT transformation that takes the
paths
file as input and produces a new XSLT transformation as output. This new XSLT will transform from yourroot
input XML to the annotated copy output XML.Notes:
template/@match
attributes, the full sophistication of@match
ing is available efficiently. I've included an attribute value test as an example.template/@match
does here.This input XML that specifies XPaths and annotations:
When input to this meta XSLT transformation:
Will produce this XSLT transformation:
Which, when provided this input XML file:
Will produce the desired output XML file:
Assuming Saxon 9 PE or EE, it should also be possible to make use XSLT 3.0 and of
xsl:evaluate
as follows:Here is an edited version of the originally posted code that uses the XSLT 3.0 map feature instead of a temporary document to store the association between the generated id of a node found by dynamic XPath evaluation and the annotation:
As the first stylesheet, it needs Saxon 9.5 PE or EE to be run.