XSLT pipeline : Error XPDY0002 - The context item for axis step fn:root(...)/element() is absent - saxon

Please, I need some help dealing with saxon api :)
I create a pipeline with 2 XsltTransform of the same xslt and when i run transform i get this error :
2019-01-24 11:32:15,673 [pool-2-thread-1] INFO e.s.e.x.XsltListener - file
2019-01-24 11:32:15,674 [pool-2-thread-1] INFO e.s.e.x.XsltListener - Error
XPDY0002 while evaluating xsl:message content: The context item for axis
step fn:root(...)/element() is absent
here is my xslt :
<xsl:stylesheet exclude-result-prefixes="#all" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:variable name="supp" as="xs:string" select="root()/*/name()"/>
<xsl:template match="/">
<xsl:message select="$supp"/>
<file/>
</xsl:template>
the first XsltTransform work fine but It seems that i have no context node during the second XstTransform running.
I use :
transformer1.setSource(source) : source is a SAXSource
transformer1.setDestination(transformr2)
transformr2.setDestination(serialiser)
According to documentation (XsltTransform.setInitialContextNode):
This value is ignored in the case where the XsltTransformer is used as the Destination of another process. In that case the initial context node will always be the document node of the document that is being streamed to this destination.
Thanks for your Help

In general in XSLT 3 you need to distinguish between the initial match selection https://www.w3.org/TR/xslt-30/#dt-initial-match-selection which is used to decide which template to apply first and the global context item https://www.w3.org/TR/xslt-30/#dt-global-context-item that is used to evaluate global parameters and variables. I think you seem to expect that in your second stylesheet the result of your first acts as both but it seems, at least in your setup, Saxon does not assume that but only sets your initial match selection to the result of the first stylesheet. So try moving the <xsl:variable name="supp" as="xs:string" select="root()/*/name()"/> into the template e.g.
<xsl:template match="/">
<xsl:variable name="supp" as="xs:string" select="root()/*/name()"/>
<xsl:message select="$supp"/>
<file/>
</xsl:template>
I am not sure there is another way, at least in the case of chaining two streaming transformations you can't the second stylesheet expect to have access to the whole result tree of the first to be used to evaluate global parameters or variables.

Related

why am I getting Required cardinality of value of variable $depts is exactly one; supplied value has cardinality more than one

Trying to figure out some homework here and the online teacher has never responded to any questions I ask.
I keep getting an error when I try to process the xml document.
"XTTE0570: Required cardinality of value of variable $depts is exactly one; supplied value has cardinality more than one"
The case problem instructions:
First, create a template named getemployees.
Within the getEmployees template, create a variable named depts containing a sequence of the following text strings representing the department codes for Lucy’s sample data: ‘a00’, ‘c01’, ‘d11’, ‘d21’, ‘e11’, and ‘e21’.
After the line to create the depts variable, create the departments element.
Within the departments element, insert a for-each loop that loops through each entry in the
depts sequence.
For each entry in the depts sequence do the following:
a. Create a variable named currentDept equal to the current item in the depts sequence.
b. Create an element named department with an attribute named deptiD whose value is equal to the value of the currentDept variable.
c. Use the doc() function to reference the “deptcurrent.xml” file, where current is the value of the currentDept variable. (Hint: Use the concat() function to combine the text strings for “dept”, the currentDept variable, and the text string “.xml”.)
d. Use the copy-of element to copy the contents of the employees element and its descendants to the department element.
Save your changes to the file and then use your XSLT 2.0 processor to generate the result
document horizons.xml by applying the getEmployees template within the alldepartments.xsl
style sheet.
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template name="getEmployees">
<xsl:variable name="depts" select="('a00', 'c01', 'd11', 'd21', 'e11', 'e21')" as="xs:string" />
<departments>
<xsl:for-each select="$depts">
<xsl:variable name="currentDept">
<xsl:value-of select="." />
</xsl:variable>
<department deptID="{$currentDept}">
<xsl:value-of select="doc(concat('dept',$currentDept, '.xml'))" />
<xsl:copy-of select="employees" />
</department>
</xsl:for-each>
</departments>
</xsl:template>
</xsl:stylesheet>
Should generate something similar to:
<?xml version="1.0" encoding="UTF-8"?>
<departments>
<department dept="a00">
<employees>
<employee empID="10">
<firstName>Marylin</firstName>
<middleInt>A</middleInt>
<lastName>Johnson</lastName>
<department>A00</department>
<phone>3978</phone>
<email>Johnson.60#example.com/horizons</email>
<dateHired>2000-01-01</dateHired>
<title>President</title>
<edLevel>18</edLevel>
<gender>F</gender>
<birthDate>1968-08-24</birthDate>
<salary>121300</salary>
<bonus>2300</bonus>
<commission>9700</commission>
</employee>
<employee empID="40">
<firstName>Heather</firstName>
<middleInt>D</middleInt>
<lastName>Gordon</lastName>
<department>A00</department>
<phone>3915</phone>
<email>Gordon.59#example.com/horizons</email>
<dateHired>2009-03-01</dateHired>
<title>Manager</title>
<edLevel>18</edLevel>
<gender>F</gender>
<birthDate>1986-06-03</birthDate>
<salary>85400</salary>
<bonus>1700</bonus>
<commission>6500</commission>
</employee>
</employees>
</department>
</departments>
If you use the as attribute on xsl:variable to declare the type of your variable then the value you select needs to fit that declaration, so given that you have a sequence of strings you need to use <xsl:variable name="depts" select="('a00', 'c01', 'd11', 'd21', 'e11', 'e21')" as="xs:string*" />.
Additionally the
<xsl:copy-of select="employees" />
inside the for-each over a string sequence doesn't make sense (and explain the error you get after correcting the variable type), there you simply want
<xsl:copy-of select="doc(concat('dept', ., '.xml'))/employees" />

xslt how to read the document-node()

I have a xml file in which one of the element has the CDATA as the value. I put the CDATA value into a variable which I can see is value type of document-node(1) when i debug my code from oXygen. How do I iterate the document-node()?
copy can give me a new xml file. but what I need is not a new file. I only need to read certain nodes and generate a report based on the values on those nodes. so I directly copy the CDATA to my variable and thought I can manipulate it.
I tried to use substring to read the variable things but failed.
I tried to use document(variable) to open the variable but Oxygen give me the debug-error of FODC0002:I/O error reported by xml parser processing file.
here the file is my variable which looks like a xml file
I did google search for the error but only got bench of non-closed questions like Oxygen throw I/O error when use document().
Would anybody let me know what's going wrong? or give me a better solution?
I also tried parse-xml() but I got the following error from Saxon:
F[Saxon-EE9.5.1.5] the processing instruction target matching "[xX][mM][lL]" is not allowed
F[Saxon-EE9.5.1.5] FODC0006: First argument to parse-xml() is not a well formed and namespace-well-formed XML document.
my code to use parse-xml is as below:
<xsl:template match="data"
<xsl:for-each select="parse-xml(root/outsideData)//nodeLevel1/nodeLevel2">
Could anyone give me a sample about how to use parse-xml()? I did google search but didn't find useful samples.
Thanks very much!
A piece of my data is like the following:
<root>
<outsideData id="123">
<child1 key="124375438"/>
<![CDATA[ <?xml version=1.0 encoding="UTF-8"?><insideData xmlns:xlink="http://www.w3.org/1999/xlink">
<nodeLevel1>
<nodeLevel21>packing</nodeLevel21>
<nodeLevel22 ref="12343-454/560" xlink:href="URN:X-MN:DD%3FM=B888%26SDC=A%26CH=79% .../>
</nodeLevel1>
]]>
</outsideData>
</root>
I want to get the inside CDATA <nodeLevel22> #ref and #xlink which will get DD-FM-B888-26-79
My variables are:
<xsl:for-each select="/root/outsideData">
<xsl:variable name="insideData">
<xsl:value-of select="." disable-output-escaping="yes"/>
</xsl:variable>
<xsl:variable name="Data">
<xsl:value-of
select="normalize-space(substring-after($insideData,'?>'))"
disable-output-escaping="yes"/>
</xsl:variable>
</xsl:foreach>
From the debug I can see that the variable insideData and Data are both value type of document-node(1)
Martin's solution works for me very well :)
But I'm still wondering why the following doesn't work:
<xsl:variable name="insideData">
<xsl:value-of select="." disable-output-escaping="yes"/>
</xsl:variable>
<ref>
<xsl:value-of select="substring-before(substring-after($insideData, '<nodeLevel22 ref'),>/>')"/>
</ref>
Here I got empty <ref/>
If you do <xsl:variable name="varName"><xsl:value-of select="..."/><xsl:variable> then you are creating a temporary document fragment that contains a single text with the string contents of the item(s) selected in the value-of. That does not make sense in most cases, doing <xsl:variable name="varName" select="..."/> is usually sufficient.
As for parsing the contents of the outsideData element with parse-xml, there is indeed not only the escaped XML document inside that element but white space as well, thus if you try to parse the contents as XML you get that error as white space before the XML declaration is not allowed. The whole approach of stuffing the XML into a CDATA section with an element with mixed contents is flawed in my view, if you want to store escaped XML into a CDATA then you should make sure that you use a single element that contains nothing but the CDATA section which then only contains the XML markup with no leading white space.
If you can't change the creation of the input data then you will need to make sure you pass in only that part of the string contents of the element to parse-xml that is a well-formed XML document, so you need some way to strip the white space before the XML declaration doing e.g.
<xsl:for-each select="/root/outsideData">
<xsl:variable name="xml-string" select="replace(., '^\s+', '')"/>
<xsl:variable name="xml-doc" select="parse-xml($xml-string)"/>
<!-- now output data e.g. -->
<xsl:value-of select="$xml-doc//nodeLevel1/nodeLevel22/#ref"/>
...
</xsl:for-each>
Untested but should show the right direction as far as trying to use parse-xml.

apply templates select substring after

I've an XML line like the below.
<title>I. DEFINITION</title>
Here what i'm doing getting the value before '.', this is fine but i want to apply-templates for the content after '.'. i'm unable to know how do i do it. i'm using the below XSLT line.
<xsl:apply-templates select="substring-after(.,'. ')"/>
when i use it, an error is thrown and it is
XSLT 2.0 Debugging Error: Error: file:///C:/Users/u0138039/Desktop/Proview/HK/ArchboldHK2014/XSLT/Chapters.xsl:508: Not a node item - item has type xs:string with value 'DEFINITION' - Details: - XTTE0520: The result of evaluating the 'select' attribute of the <xsl:apply-templates> instruction may only contain nodes
please let me know how i can apply-templates on content after '.'
Thanks.
You can try this template
<xsl:template match="title">
<xsl:copy>
<label><xsl:value-of select="substring-before(., '. ')"/></label>
<caption>
<xsl:variable name="slicetext" select="substring-after(current()/text()[1], '. ')"/>
<xsl:value-of select="$slicetext"/><xsl:apply-templates select="text()[position() > 1]|child::node()[not(self::text())]"/>
</caption>
</xsl:copy>
</xsl:template>
With XSLT 1.0 and 2.0 you can only write and apply-templates for nodes, not for primitive values like strings. I think this changes in XSLT 3.0.
In XSLT 2.0, to process the result of substring-after further, you would need to write a function or a named template taking a string parameter.
If you really want to apply a template you first would need to create a temporary text node with xsl:variable.

Can I apply a character map to a given node?

If I look at the xslt specs it seems a character map applies to the whole document, bit is it also possible to use it on a given node, or within a template ?
Example : I have a node containing look up values, but they might contain characters that don't play well with regular expressions when using it in another template. For now I use a replace functionwhich works well,, but after a few characters that becomes pretty hard to read or maintain. So if I have something like this :
<xsl:variable name="myLookup" select="
replace(
replace(
replace(
replace(
string-join(/*/lookup/*, '|'),
'\[','\\['),
'\]','\\]'),
'\(','\\('),
'\)','\\)')
"/>
is there a way to achieve something like below fictitious example ?
<xsl:character-map name="escapechar">
<xsl:output-character character="[" string="\[" />
<xsl:output-character character="]" string="\]" />
<xsl:output-character character="(" string="\(" />
<xsl:output-character character=")" string="\)" />
</xsl:character-map>
<xsl:variable name="myLookup" select="string-join(/*/lookup/*, '|')" use-character-map="escapechar"/>
I know this is not working at all, it is just to make my request a bit visual.
Any idea ?
I think character maps in XSLT 2.0 are a serialization feature to be applied when a result tree is serialized to a file or stream so I don't see how you could apply one to a certain string or certain node during a transformation.
As for escaping meta characters of regular expression patterns, maybe http://www.xsltfunctions.com/xsl/functx_escape-for-regex.html helps.
Character maps is only a serialization feature, which means that it is only executed when the final output of a transformation is produced. However, you can significantly simplify your current code.
Just use:
replace($pStr, '(\[|\]|\(|\))','\\$1')
Here is a complete example:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="my:my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<xsl:value-of select="my:escape(.)"/>
</xsl:template>
<xsl:function name="my:escape" as="xs:string">
<xsl:param name="pStr" as="xs:string"/>
<xsl:value-of select="replace($pStr, '(\[|\]|\(|\))','\\$1')"/>
</xsl:function>
</xsl:stylesheet>
When this transformation is applied on the following XML document:
<t>([a-z]*)</t>
the wanted, correct result is produced:
\(\[a-z\]*\)

How can I get xslt to indent xml (from Ant)?

From what I understand having looked around for an answer to this the following should work:
<xslt basedir="..." destdir="..." style="xslt-stylesheet.xsd" extension=".xml"/>
Where xslt-stylesheet.xsd contains the following:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
Unfortunately while most formatting is applied (spaces are stripped, newlines entered, etc.), indentation is not and every element is along the left side in the file. Is this an issue with the xslt processor Ant uses, or am I doing something wrong? (Using Ant 1.8.2).
It might help to set some processor-specific output options, though you should note that these may vary depending on the XSLT processor that you're using.
For example, if you're using Xalan, it defines an indent-amount property, which seems to default to 0.
To override this property at runtime, you can declare xalan namespace in your stylesheet and override using the processor-specific attribute indent-amount in your output element as follows:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xalan="http://xml.apache.org/xalan">
<xsl:output method="xml"
encoding="UTF-8"
indent="yes"
xalan:indent-amount="2"/>
This example is from the Xalan usage patterns documentation at http://xml.apache.org/xalan-j/usagepatterns.html
If you do happen to be using Xalan, the documentation also says you can change all of the output preferences globally by setting changing the file org/apache/serializer/output_xml.properties in the serializer jar.
In the interest of completeness, the complete set of Xalan-specific xml output properties defined in that file (Xalan 2.7.1) are:
{http://xml.apache.org/xalan}indent-amount=0
{http://xml.apache.org/xalan}content-handler=org.apache.xml.serializer.ToXMLStream
{http://xml.apache.org/xalan}entities=org/apache/xml/serializer/XMLEntities
If you're not using Xalan, you might have some luck looking for some processor-specific output properties in the documentation for your XSLT processor
Different XSLT processors implement indent="yes" in different way. Some indent properly, while others only put the element starting on a new line. It seems that your XSLT processor is among the latter group.
Why is this so?
The reason is that the W3C XSLT Specification allows significant leeway in what indentation could be produced:
"If the indent attribute has the value yes, then the xml output
method may output whitespace in addition to the whitespace in the
result tree (possibly based on whitespace stripped from either the
source document or the stylesheet) in order to indent the result
nicely; if the indent attribute has the value no, it should not
output any additional whitespace. The default value is no. The xml
output method should use an algorithm to output additional whitespace
that ensures that the result if whitespace were to be stripped from
the output using the process described in [3.4 Whitespace Stripping]
with the set of whitespace-preserving elements consisting of just
xsl:text would be the same when additional whitespace is output as
when additional whitespace is not output.
NOTE:It is usually not safe to use indent="yes" with document types that include element types with mixed content."
Possible solutions:
Start using another XSLT processor. For example, Saxon indents quite well.
Remove the <xsl:strip-space elements="*"/> directive. If there are whitespace-only text nodes in the source XML, they would be copied to the output and this may result in a better-looking indented output.
I don't know if ant is OK. But concerning your XSLT :
When you use the copy-of on an element, your XSLT processor does not indent. If you change your XSLT like this, your XSLT processor will may be manage to indent :
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|#*">
<xsl:copy>
<xsl:apply-templates select="node()|#*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
This XSLT will go through the whole XML tree and indents each element it creates.
EDIT after comment :
You can see the following question to change your XSLT processor, maybe it will solve your problem : How to execute XSLT 2.0 with ant?
You can try adding the {http://xml.apache.org/xslt}indent-amount output property in ant, something like this:
<target name="applyXsl">
<xslt in="${inputFile}" out="${outputFile}" extension=".html" style="${xslFile}" force="true">
<outputproperty name="indent" value="yes"/>
<outputproperty name="{http://xml.apache.org/xslt}indent-amount" value="4"/>
</xslt>
</target>

Resources