Create XPath with dynamic variable in runtime (XSL version 1.0) -> then use it as select - mapping

I have already read some pages here about this topic but nothing matched my issue so far.
So my problem is that I need to create an xpath string dynamically and use that xpath string in the select of a "<xsl:value-of"-tag to select the appropriate value from the xml document. But instead it is showing the string of the xpath itself as shown below
So I have a simple XML Document (just a small example to show the issue. The original is much larger containing more fields)
<s0:RootNode>
<s0:HEADER>
<s0:DocumentDate>2022-10-13</s0:DocumentDate>
<s0:DocumentID>123456</s0:DocumentID>
</s0:HEADER>
</s0:RootNode>
Here I create the xPath string dynamically:
<!-- This ('DocumentID') will be a dynamic value later on -->
<xsl:variable name="varField" select="'DocumentID'"/>
<!-- The output of that variable is the correct xPath 's0:HEADER/s0:DocumentID/text()' I want to use. -->
<xsl:variable name="xPath" select="concat('s0:HEADER/s0:',$varField,'/text()')" />
So my map
<Value>
<xsl:value-of select="$xPath" />
</Value>
Will produce the output:
<Value>s0:HEADER/s0:DocumentID/text()</Value>
instead of:
<Value>123456</Value>
So how can I 'force' to select the value 123456 based on the generic xpath string instead of the xPath string itself?
Many thanks for your help.

You could just make the element name variable. You might not need s0:RootNode. Just adjust based on your context.
<!-- This ('DocumentID') will be a dynamic value later on -->
<xsl:variable name="varField" select="'DocumentID'"/>
<xsl:variable name="test">
<Value>
<xsl:value-of select="s0:RootNode/s0:HEADER/s0:*[local-name() = $varField]" />
</Value>
</xsl:variable>

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" />

Any way to access the value from xml

I'm trying to access values from my xml file using "title" xpath without using /Para000_* because _1,_2 is dynamic.
Is there any way to access the value without using para number please help me
I need value only "Mango" but i'm getting "Mango Orange" values
I have an xml as follows:
<Content code="" title="Food" type="Fruits" paraCode="2">
<props>
<para001_2 title="F1">Mango</para001_2>
<para002_2 title="F2">Grape</para002_2>
</props>
</Content>
<Content code="" title="Food" type="Fruits" paraCode="2">
<props>
<para001_2 title="F1">Orange</para001_2>
<para002_2 title="F2">Grape</para002_2>
</props>
</Content>
tried XSLT as follows:
<xsl:variable name="FruitName" select="/Content/props/*[#title = 'F1']"/>
Result:
Mango
Use this
<xsl:variable name="FruitName" select="/Content/props/*[#title = 'F1'][not(preceding::Content/props/*[#title = 'F1'])]"/>
Please mention on what basis/condition you want access the node <Content>
For the current input given, to access the first node's title
The solution can be:
<xsl:value-of select="root/Content/props/*[1][#title = 'F1']"/>

xpath expression to select specific xml nodes that are available in a file

I was trying to find the out a way for my strange problem.
How to write an xpath to select specific xml nodes that are available in another text file.
For Instance,
<xsl:for-each select="SUBSCRIBER_PROFILE_LIST/SUBSCRIBER_PROFILE_INFO[GROUP_NAME eq (group name list in a text file as input)]">
For example,
<xsl:for-each select="SUBSCRIBER_PROFILE_LIST/SUBSCRIBER_PROFILE_INFO[GROUP_NAME eq collection('select_nodes.txt')]">
select_nodes.txt contains list of string that can be selected only
For example
ABC
IJK
<SUBSCRIBER>
<MSISDN>123456</MSISDN>
<SUBSCRIBER_PROFILE_LIST>
<SUBSCRIBER_PROFILE_INFO>
<PROFILE_MSISDN>12345</PROFILE_MSISDN>
<GROUP_NAME>ABC</GROUP_NAME>
<GROUP_ID>18</GROUP_ID>
</SUBSCRIBER_PROFILE_INFO>
<SUBSCRIBER_PROFILE_INFO>
<PROFILE_MSISDN>456778</PROFILE_MSISDN>
<GROUP_NAME>DEF</GROUP_NAME>
<GROUP_ID>100</GROUP_ID>
</SUBSCRIBER_PROFILE_INFO>
<SUBSCRIBER_PROFILE_INFO>
<PROFILE_MSISDN>78876</PROFILE_MSISDN>
<GROUP_NAME>IJK</GROUP_NAME>
<GROUP_ID>3</GROUP_ID>
</SUBSCRIBER_PROFILE_INFO>
</SUBSCRIBER>
XSLT2 has limited functionality for parsing arbitrary text files. I would suggest:
Make the select_nodes.txt an XML file and load it using the doc() function:
<xsl:variable name="group_names" as="xs:string *"
select="doc('select_nodes.xml')/groups/group"/>
with select_nodes.xml looking like this:
<?xml version="1.0" encoding="UTF-8"?>
<groups>
<group>ABC</group>
<group>IJK</group>
</groups>
Pass the group names as a stylesheet parameter. (How you do this depends on which XSLT engine you're using and whether it's through the command line or an API.) If it's through an API, then you may be able to pass the values in directly as xs:string-typed objects. Otherwise you'll have to parse the parameter:
<xsl:param name="group_names_param"/>
<!-- Assuming the input string is a whitespace-separated list of names -->
<xsl:variable name="group_names" as="xs:string *"
select="tokenize($group_names_param, '\s+')"/>
In either case your for-each expression would then look like this:
<xsl:for-each select="
SUBSCRIBER_PROFILE_LIST/SUBSCRIBER_PROFILE_INFO[GROUP_NAME = $group_names]">
<!-- Do something -->
</xsl:for-each>

Using Schematron QuickFixes to tag individual words in mixed content elements

I have an xml file that looks like this (simplifed):
<defs>
<def>Pure text</def>
<def>Mixed content, cuz there is also another: <element>element inside</element> and more.</def>
<def><element>Text nodes within elements other than def are ok.</element></def>
<defs>
I am trying to write a Shematron rule with quick fixes that would enable me to take each individual word in defs with mixed content and wrap them each in <w> elements as well as wrap punctuation characters in <pc> elements. In other words, after applying the quick fixes I would get
<defs>
<def>Pure text.</def>
<def><w>Mixed</w> <w>content</w><pc>,</pc> <w>cuz</w> <w>there</w> <w>is</w> <w>also</w> <w>another</w><pc>:</pc> <element>element inside</element> <w>and</w> <w>more</w><pc>.</pc></def>
<def><element>Text nodes within elements other than def are ok.</element></def>
<defs>
Spaces between <w>s and <pc>s are ok.
Now, identifying mixed content is easy — I think I am getting that right. The problem is I don't know how to tokenize the strings within Schematron and then apply a fix to each token. This is how far I've gotten:
<sch:pattern id="mixed">
<sch:rule context="def[child::text()][child::*]">
<sch:report test="tokenize(child::text(), '\s+')" sqf:fix="mix_in_def">
Element has mixed content
<!-- the above this gives me the error: a sequence of more than one item is not allowed as the first argument of tokenize-->
</sch:report>
<sqf:fix id="mix_in_def">
<sqf:description>
<sqf:title>Wrap words in w</sqf:title>
<sqf:p>Fixes the mixed content in def by treating each non-tagged string as w.</sqf:p>
</sqf:description>
<sqf:replace match="." node-type="element" target="w">
<!--how do i represent the content of the matched token?-->
</sqf:replace>
<!-- also do i create an altogether separate rule for punctuation?-->
</sqf:fix>
</sch:rule>
</sch:pattern>
Any tips would be greatly appreciated.
Tench
You can use XSL, look at this example (it is explained in code comments):
<sch:pattern id="mixed">
<!-- Your context is now def => this makes easier add new def reports -->
<sch:rule context="def">
<!-- So now you report every def that has text and elements -->
<sch:report test="child::text() and child::*" sqf:fix="mix_in_def">
Element has mixed content
<!-- What you were doing before where causing error because you were passing a sequence of text nodes to tokenize (it expects a string) -->
</sch:report>
<sqf:fix id="mix_in_def">
<sqf:description>
<sqf:title>Wrap words in w</sqf:title>
<sqf:p>Fixes the mixed content in def by treating each non-tagged string as w.</sqf:p>
</sqf:description>
<!-- Replace every mixed text node of this def (this is called for every matched node) -->
<sqf:replace match="child::text()">
<!-- Tokenize this text node => for each token choose... -->
<xsl:for-each select="tokenize(., '\s+')">
<!-- For this token choose -->
<xsl:choose>
<!-- If text is one of this (,.:) Please note that you are using \s+ to separate tokens. So a comma is only a token if it is separated by spaces -->
<xsl:when test=". = (',', '.', ':', 'is')"> <!-- "is" just to test results -->
<pc><xsl:value-of select="."/></pc>
</xsl:when>
<!-- Otherwise wrap it in <w> -->
<xsl:otherwise>
<w><xsl:value-of select="."/></w>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</sqf:replace>
</sqf:fix>
</sch:rule>
</sch:pattern>
You'll have to adapt this to your specific problem but I think this will help you.

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.

Resources