Concate after Choose XSLT1.0 or 2.0 - xslt

Still new to this forum and XSLT, already searched but could not find the correct solution.
i am trying to get the right concat after the choose, if i match the condition 208 or 906 is still get LX1234 as combination, it always ends up on the otherwise as solution. the XSLT is build in 2.0 so both solutions will work for me.
<xsl:for-each select="XXX/Envelope/PickingList/Line/Lot">
<articleLine type="tag">
<articleCode>
<xsl:choose>
<xsl:when test="XXX/Envelope/GLN_Supplier =208">
<xsl:value-of select="concat('AV',../ArticleCodeSupplier)"/>
</xsl:when>
<xsl:when test="XXX/Envelope/GLN_Supplier =906">
<xsl:value-of select="concat('KR',../ArticleCodeSupplier)"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat('LX',../ArticleCodeSupplier)"/>
</xsl:otherwise>
</xsl:choose>
</articleCode>
Edit XML input, thank you for pointing that out #michael.hor257k
<?xml version='1.0' encoding='ISO-8859-1'?>
<XXX>
<Envelope>
<InterchangeControlReference>995566</InterchangeControlReference>
<GLN_Supplier>906</GLN_Supplier>
<GLN_Customer>541</GLN_Customer>
<PickingList>
<PickingListNumber>9</PickingListNumber>
<PickingDate>2019-08-01</PickingDate>
<OrderNumberSupplier>12345</OrderNumberSupplier>
<OrderNumberCustomer>EDI Test 1</OrderNumberCustomer>
<EarliestDeliveryDate>2019-10-09</EarliestDeliveryDate>
<EarliestDeliveryTime>14:13:39</EarliestDeliveryTime>
<LastDeliveryDate>2019-10-09</LastDeliveryDate>
<LastDeliveryTime>14:13:39</LastDeliveryTime>
<GLN_Supplier>215</GLN_Supplier>
<GLN_WarehouseAddressSupplier>541</GLN_WarehouseAddressSupplier>
<GLN_Customer>000</GLN_Customer>
<GLN_DeliveryAddressCustomer>000</GLN_DeliveryAddressCustomer>
<GLN_CarrierAddressCustomer></GLN_CarrierAddressCustomer>
<DeliveryName>CLIENTNAME</DeliveryName>
<DeliveryNameContactperson></DeliveryNameContactperson>
<DeliveryTelephoneNumber></DeliveryTelephoneNumber>
<DeliveryAddress>CLIENTADDRESS</DeliveryAddress>
<DeliveryAddress2></DeliveryAddress2>
<DeliveryHouseNumber>0</DeliveryHouseNumber>
<DeliveryHouseNumberExtra></DeliveryHouseNumberExtra>
<DeliveryPostalCode>1111 aa</DeliveryPostalCode>
<DeliveryCity>PLACE</DeliveryCity>
<DeliveryCountryISO>NL</DeliveryCountryISO>
<DeliveryCustomsExcise></DeliveryCustomsExcise>
<DeliveryMethod>DDP</DeliveryMethod>
<DeliveryIncoterm>DDP</DeliveryIncoterm>
<DeliveryIncotermCity></DeliveryIncotermCity>
<Remarks_Pickinglist>REMARKS WAREHOUSE</Remarks_Pickinglist>
<Remarks_Packinglist>REMARKS FREIGHTBILL</Remarks_Packinglist>
<Remarks_Delivery></Remarks_Delivery>
<CustomsExcise>true</CustomsExcise>
<Test>false</Test>
<Line>
<LineNumber>1</LineNumber>
<EAN_Article>528</EAN_Article>
<ArticleCodeSupplier>1234</ArticleCodeSupplier>
<ArticleCodeCustomer></ArticleCodeCustomer>
<UnitToPick>Fles</UnitToPick>
<ArticleDescription>VINE WINE</ArticleDescription>
<QuantityToPick>21</QuantityToPick>
<QuantityToPickInOrderUnit>21</QuantityToPickInOrderUnit>
<UnitOrdered>Fles</UnitOrdered>
<Lot>
<LotCode>72</LotCode>
<BatchCode>3</BatchCode>
<YearOfProduction>2017</YearOfProduction>
<QuantityToPick>21</QuantityToPick>
</Lot>
</Line>
<Line>
<LineNumber>2</LineNumber>
<EAN_Article>081</EAN_Article>
<ArticleCodeSupplier>5678</ArticleCodeSupplier>
<ArticleCodeCustomer></ArticleCodeCustomer>
<UnitToPick>Fles</UnitToPick>
<ArticleDescription>CHAMPAGNE</ArticleDescription>
<QuantityToPick>10</QuantityToPick>
<CountryOfOriginISO>ES</CountryOfOriginISO>
<QuantityToPickInOrderUnit>10</QuantityToPickInOrderUnit>
<UnitOrdered>Fles</UnitOrdered>
<Lot>
<LotCode>5</LotCode>
<BatchCode>4</BatchCode>
<YearOfProduction>2019</YearOfProduction>
<QuantityToPick>10</QuantityToPick>
<CountryOfOriginISO>ES</CountryOfOriginISO>
</Lot>
</Line>
</PickingList>
</Envelope>
</XXX>

The instruction:
<xsl:for-each select="XXX/Envelope/PickingList/Line/Lot">
puts you in the context of Lot. From this context, the test in:
<xsl:when test="XXX/Envelope/GLN_Supplier =208">
will return false, because the relative path XXX/Envelope/GLN_Supplierselects nothing. You will get a different result if you make the path an absolute one:
<xsl:when test="/XXX/Envelope/GLN_Supplier =208">
Of course, it would be more efficient to do this test once outside the xsl:for-each block and make the result available in a variable - for example:
<xsl:template match="/XXX">
<output>
<xsl:variable name="articleCodePrefix">
<xsl:choose>
<xsl:when test="Envelope/GLN_Supplier=208">AV</xsl:when>
<xsl:when test="Envelope/GLN_Supplier=906">KR</xsl:when>
<xsl:otherwise>LX</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<xsl:for-each select="Envelope/PickingList/Line/Lot">
<articleLine type="tag">
<articleCode>
<xsl:value-of select="$articleCodePrefix"/>
<xsl:value-of select="../ArticleCodeSupplier"/>
</articleCode>
</articleLine>
</xsl:for-each>
</output>
</xsl:template>

Related

idiomatic alternative to choose -> test -> value-of (XSLT 1.0)

In the work I do I seem to see a lot of code liek this..
<xsl:choose>
<xsl:when test="long_xpath_to_optional/#value1">
<xsl:value-of select="long_xpath_to_optional/#value"/>
</xsl:when>
<xsl:when test="another_long_xpath_to_optional/#value">
<xsl:value-of select="another_long_xpath_to_optional/#value"/>
</xsl:when>
<etc>
</etc>
<otherwise>
<xsl:value-of select="default_long_xpath_to_value"/>
</otherwise>
</xsl:choose>
its very long and very repetitive.
When I'm were working in some other (psuedo) language I would go
let values = concat(list(long_xpath_to_optional_value),list(another_long_xpath_to_optional_value))
let answer = tryhead(values,default_long_xpath_to_value)
i.e. create a list of values in priority order, and then take the head.
I only evaluate each path once
how would you do something similar in XSLT 1.0 (we can use node-sets).
I was wondering if you can create a node-set somehow
You can - but it's not going to be any shorter:
<xsl:variable name="values">
<xsl:apply-templates select="long_xpath_to_optional/#value" mode="values"/>
<xsl:apply-templates select="another_long_xpath_to_optional/#value" mode="values"/>
<xsl:apply-templates select="default_long_xpath_to_value/#value" mode="values"/>
</xsl:variable>
<xsl:value-of select="exsl:node-set($values)/value[1]" xmlns:exsl="http://exslt.org/common"/>
and then:
<xsl:template match="#value" mode="values">
<value>
<xsl:value-of select="."/>
</value>
</xsl:template>
But at least the repetition is eliminated.
Alternatively, you could do:
<xsl:template match="#value" mode="values">
<xsl:value-of select="."/>
<xsl:text>|</xsl:text>
</xsl:template>
and then:
<xsl:value-of select="substring-before($values, '|')"/>
To use variables you write
<xsl:variable name="value1" select="long_xpath_to_optional/#value1"/>
<xsl:variable name="value2" select="another_long_xpath_to_optional/#value"/>
<xsl:variable name="value3" select="default_long_xpath_to_value"/>
and then in XPath 2 or 3 all you would need is ($value1, $value2, $value3)[1] or head(($value1, $value2, $value3)) but in XSLT 1 with XPath 1 all you can write as a single expression is ($value1 | $value2 | $value3)[1] which sorts in document order so unless the document order is the same as your test order this wouldn't work to check the values; rather you would need to maintain the
<xsl:choose>
<xsl:when test="$value1">
<xsl:value-of select="$value1"/>
</xsl:when>
<xsl:when test="$value2">
<xsl:value-of select="$value2"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$value3"/>
</xsl:otherwise>
</xsl:choose>
Of course in XPath 2 you wouldn't really need the variables and could use (long_xpath_to_optional/#value1, another_long_xpath_to_optional/#value, default_long_xpath_to_value)[1] as well directly.

Why is this XSLT variable returning undefined?

I'm trying to write an XSLT function to select between some dates. I have parameters that are being converted to xs:date and then used to get the number of days between two of them, and format them appropriately. For some reason, the termDate variable is being reported as undefined, even though I can see in the Variables and Nodes/Values Set panels in Oxygen that the parameter references and element that does have a value.
<xsl:function name="my:getStatusDate">
<xsl:param name="rehire"/>
<xsl:param name="term"/>
<xsl:param name="hire"/>
<xsl:variable name="rehireDate" select="xs:date($rehire)" as="xs:date"/>
<xsl:variable name="termDate" select="xs:date($term)" as="xs:date"/>
<xsl:variable name="hireDate" select="xs:date($hire)" as="xs:date"/>
<xsl:variable name="dayDiffTermRehire" select="days-from-duration($termDate - $rehireDate)" as="xs:integer"/>
<xsl:choose>
<xsl:when test="$term != '' and not($term)">
<xsl:choose>
<xsl:when test="$dayDiffTermRehire > xs:integer(91)">
<xsl:value-of select="format-date($rehireDate, '[M01]/[D01]/[Y0001]')"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="format-date($hireDate, '[M01]/[D01]/[Y0001]')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="format-date($hireDate, '[M01]/[D01]/[Y0001]')"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>
The call site looks like this:
<ExpectedStatusEffectiveDate><xsl:value-of select="my:getStatusDate(RecentHireDate, TermDate, PreviousHireDate)"/></ExpectedStatusEffectiveDate>
A sample XML source looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Entry>
<EmployeeFirstName>John</EmployeeFirstName>
<EmployeeLastName>Doe</EmployeeLastName>
<BirthDate>1940-01-01-01:00</BirthDate>
<RecentHireDate>1970-05-20-07:00</RecentHireDate>
<PreviousHireDate>1970-05-20-07:00</PreviousHireDate>
</Entry>
<Entry>
<EmployeeFirstName>Jane</EmployeeFirstName>
<EmployeeLastName>Doe</EmployeeLastName>
<BirthDate>1970-11-25-08:00</BirthDate>
<RecentHireDate>2003-12-22-08:00</RecentHireDate>
<PreviousHireDate>1970-06-19-07:00</PreviousHireDate>
<TermDate>2000-01-13-08:00</TermDate> <!-- NOTE: this entry HAS a TermDate -->
</Entry>
</Data>
Any idea why the termDate would be undefined in BOTH cases?
I'm going to chalk this up to an Oxygen bug. I'm not sure what changed, but after isolating the function into its own stylesheet, it started working. I then copied it back into the original, and everything seemed to work.

Structural requirements when using "except" in XPATH/XSL

I am having trouble when using "except" in xpath. Here is the chunk of problem code. (I tried to simplify as much as possible without obscuring the whole problem).:
<!--First, create a variable containing some nodes that we want to filter out.
(I'm gathering elements that are missing child VALUE elements
and whose child DOMAIN and VARIABLE elements only occur once
in the parent list of elements.)
I've confirmed that this part does generate the nodes I want,
but maybe this is the incorrect result structure?-->
<xsl:variable name="badValues">
<xsl:for-each select="$root/A[not(VALUE)]">
<xsl:choose>
<xsl:when test="count($root/A[DOMAIN=current()/DOMAIN and VARIABLE=current()/VARIABLE])=1">
<xsl:copy-of select="."/>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
<!--Next Loop over the original nodes, minus those bad nodes.
For some reason, this loops over all nodes and does not filter out the bad nodes.-->
<xsl:for-each select="$root/A except $badValues/A"> ...
When you create an xsl:variable without using #select and do not specify the type with the #as, it will create the variable as a temporary tree.
You want to create a sequence of nodes, so that when they are compared in the except operator, they are "seen" as the same nodes. You can do this by specifying as="node()*" for the xsl:variable and by using xsl:sequence instead of xsl:copy-of:
<xsl:variable name="badValues" as="node()*">
<xsl:for-each select="$root/A[not(VALUE)]">
<xsl:choose>
<xsl:when test="count($root/A[DOMAIN=current()/DOMAIN
and VARIABLE=current()/VARIABLE])=1">
<xsl:sequence select="."/>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
Alternatively, if you were to use a #select and eliminate the xsl:for-each it would also work. As Martin Honnen suggested, you could use an xsl:key and select the values like this:
<xsl:key name="by-dom-and-var" match="A" use="concat(DOMAIN, '|', VARIABLE)"/>
Then change your badValues to this:
<xsl:variable name="badValues"
select="$root/A[not(VALUE)]
[count(key('by-dom-and-var',
concat(DOMAIN, '|', VARIABLE))/VARIABLE) = 1]"/>>
You can see the difference in the identity of the nodes by using the generate-id() function as you iterate over the items by executing this stylesheet:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes"/>
<xsl:template match="/">
<xsl:variable name="root" select="*" as="item()*"/>
<xsl:variable name="originalBadValues">
<xsl:for-each select="$root/A[not(VALUE)]">
<xsl:choose>
<xsl:when test="count($root/A[DOMAIN=current()/DOMAIN
and VARIABLE=current()/VARIABLE])=1">
<xsl:copy-of select="."/>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
<xsl:variable name="badValues" as="node()*">
<xsl:for-each select="$root/A[not(VALUE)]">
<xsl:choose>
<xsl:when test="count($root/A[DOMAIN=current()/DOMAIN
and VARIABLE=current()/VARIABLE])=1">
<xsl:sequence select="."/>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:variable>
<!--These are the generated ID values of all the A elements-->
<rootA>
<xsl:value-of select="$root/A/generate-id()"
separator=", "/>
</rootA>
<!--These are the generated ID values for
the original $badValues/A -->
<originalBadValues>
<xsl:value-of select="$originalBadValues/A/generate-id()"
separator=", " />
</originalBadValues>
<!--These are the generated ID values for
the correct selection of $badValues-->
<badValues>
<xsl:value-of select="$badValues/generate-id()"
separator=", " />
</badValues>
<!--The generated ID values for the result of
the except operator filter-->
<final>
<xsl:value-of select="($root/A except $badValues)/generate-id()"
separator=", "/>
</final>
</xsl:template>
</xsl:stylesheet>
Executed against this XML file:
<doc>
<A>
<VALUE>skip me</VALUE>
<DOMAIN>a</DOMAIN>
<VARIABLE>a</VARIABLE>
</A>
<A>
<DOMAIN>a</DOMAIN>
<VARIABLE>a</VARIABLE>
</A>
<A>
<DOMAIN>b</DOMAIN>
<VARIABLE>b</VARIABLE>
</A>
<A>
<DOMAIN>c</DOMAIN>
<VARIABLE>c</VARIABLE>
</A>
<A>
<DOMAIN>a</DOMAIN>
<VARIABLE>a</VARIABLE>
</A>
</doc>
It produces the following output:
<rootA>d1e3, d1e15, d1e24, d1e33, d1e42</rootA>
<originalBadValues>d2e1, d2e9</originalBadValues>
<badValues>d1e24, d1e33</badValues>
<final>d1e3, d1e15, d1e42</final>

How to store the current path in xsl?

I would like to store the path of the current node so I can reused it in an expression in XSLT. Is it possible?
<!-- . into $path? -->
<xsl:value-of select="$path" />
Hi, I would like to store the path of
the current node so I can reused it in
an expression in XSLT. Is it possible?
It is possible for any given node to construct an XPath expression that, when evaluated, selects exactly this node. In fact more than one XPath expression exists that selects the same node.
See this answer for the exact XSLT code that constructs such an XPath expression.
The problem is that this XPath expression cannot be evaluated during the same transformation in XSLT 1.0 or XSLT 2.0, unless the EXSLT extension function dyn:evaluate is used (and very few XSLT 1.0 processors implement dyn:evaluate() ).
What you want can be achieved in an easier way in XSLT using the <xsl:variable> instruction:
<xsl:variable name="theNode" select="."/>
This variable can be referenced anywhere in its scope as $theNode, and can be passed as parameter when applying or calling templates.
No, this is not possible with vanilla XSLT 1.0. There is no easy way to retrieve an XPath expression string for a given node, and there is definitely no way to evaluate a string that looks like XPath as if it was XPath.
There are extensions that support dynamic evaluation of XPath expressions, but these are not compatible with every XSLT processor.
In any case, if you provide more detail around what you are actually trying to do, there might be another way to do it.
As #Dimitre and #Tomalak have point out, I don't think it has some value in the same transformation to obtain a string representing an XPath expression for a given node, and then select the node "parsing" such string. I could see some value in performing those operations in different transformations.
Besides that, this stylesheet:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:for-each select=".|//node()|//#*">
<xsl:variable name="vPath">
<xsl:apply-templates select="." mode="getPath"/>
</xsl:variable>
<xsl:value-of select="concat($vPath,'
')"/>
<xsl:call-template name="select">
<xsl:with-param name="pPath" select="$vPath"/>
</xsl:call-template>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
<xsl:template match="/|node()|#*" mode="getPath" name="getPath">
<xsl:apply-templates select="parent::*" mode="getPath"/>
<xsl:text>/</xsl:text>
<xsl:choose>
<xsl:when test="self::*">
<xsl:value-of select="concat(name(),'[',
count(preceding-sibling::*
[name() =
name(current())]) + 1,
']')"/>
</xsl:when>
<xsl:when test="count(.|../#*)=count(../#*)">
<xsl:value-of select="concat('#',name())"/>
</xsl:when>
<xsl:when test="self::text()">
<xsl:value-of
select="concat('text()[',
count(preceding-sibling::text()) + 1,
']')"/>
</xsl:when>
<xsl:when test="self::comment()">
<xsl:value-of
select="concat('comment()[',
count(preceding-sibling::comment()) + 1,
']')"/>
</xsl:when>
<xsl:when test="self::processing-instruction()">
<xsl:value-of
select="concat('processing-instruction()[',
count(preceding-sibling::
processing-instruction()) + 1,
']')"/>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:template name="select">
<xsl:param name="pPath"/>
<xsl:param name="pContext" select="/"/>
<xsl:param name="pInstruction" select="'value-of'"/>
<xsl:variable name="vPosition"
select="number(
substring-before(
substring-after($pPath,
'['),
']'))"/>
<xsl:variable name="vTest"
select="substring-before(
substring-after($pPath,
'/'),
'[')"/>
<xsl:variable name="vPath" select="substring-after($pPath,']')"/>
<xsl:choose>
<xsl:when test="$vPath">
<xsl:call-template name="select">
<xsl:with-param name="pPath" select="$vPath"/>
<xsl:with-param name="pContext"
select="$pContext/*[name()=$vTest]
[$vPosition]"/>
<xsl:with-param name="pInstruction"
select="$pInstruction"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:variable name="vContext"
select="$pContext/node()
[self::*[name()=$vTest]|
self::comment()[$vTest='comment()']|
self::text()[$vTest='text()']|
self::processing-instruction()
[$vTest =
'processing-instruction()']]
[$vPosition]|
$pContext[$pPath='/']|
$pContext/#*[name() =
substring($pPath,3)]
[not($vTest)]"/>
<xsl:choose>
<xsl:when test="$pInstruction='value-of'">
<xsl:value-of select="$vContext"/>
</xsl:when>
<xsl:when test="$pInstruction='copy-of'">
<xsl:copy-of select="$vContext"/>
</xsl:when>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
With this input:
<?somePI pseudoAttributes?>
<root>
<!-- This is a comment -->
<node attribute="Value">text</node>
</root>
Output:
/
text
/processing-instruction()[1]
pseudoAttributes
/root[1]
text
/root[1]/comment()[1]
This is a comment
/root[1]/node[1]
text
/root[1]/node[1]/#attribute
Value
/root[1]/node[1]/text()[1]
text

XSLT Assignment of element value to variable: Works with Altova XML Spy, but fails in .NET app

I want to tightly grasp the hair on the back of a Microsoft employee's head, using it as leverage to pound his head forcefully and repeatedly against a hard surface! That would make me feel nearly as good as solving this problem right now.
I've got a simple XML message that looks like this:
<?xml version="1.0" encoding="utf-8"?>
<message>
<cmd id="instrument_status">
<status_id>1</status_id>
</cmd>
</message>
A web service on the device I'm working with returns several such messages and I'm converting them to a different format. For the above message the new format would look like the following:
<?xml version="1.0" encoding="UTF-8"?>
<grf:message xmlns:grf="http://www.company.com/schemas/device/version001">
<grf:messageHeader>
<grf:messageType>instrumentStatus</grf:messageType>
</grf:messageHeader>
<grf:messageBody>
<grf:instrumentStatusBody>
<grf:statusId>Running</grf:statusId>
</grf:instrumentStatusBody>
</grf:messageBody>
</grf:message>
There is a mapping for status_id integer values in the XML as follows:
status-id Meaning
========= =======
0 Ready
1 Running
2 NotReady
3 PoweringUp
4 PoweringDown
5 PoweredUp
6 PoweredDown
7 Tuning
8 Error
My XSLT is working correctly and giving me the correct output when I use Altova XMLSpy, but when I run my .NET application, I'm getting a failure at the point where the mapping for the status_id integer is converted to one of the allowable enumerated strings. Instead of getting the enumerated value, the MS XSLT processor returns an empty string and I get an empty <status_id/> element in the output XML.
The following is my XSLT code with some sections removed to reduce the amount of space:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:grf="http://www.company.com/schemas/device/version001"
exclude-result-prefixes="#default">
<xsl:template match="/">
<xsl:apply-templates select="message"/>
</xsl:template>
<xsl:template match="message">
<xsl:element name="grf:message">
<xsl:apply-templates select="/message/cmd/#id"/>
</xsl:element>
</xsl:template>
<xsl:template match="/message/cmd/#id">
<xsl:variable name="_commandType" select="/message/cmd/#id"/>
<!-- Following line works in Altova XMLSpy, but fails in .NET app. ??? -->
<xsl:variable name="_statusIdValue" select="/message/cmd/status_id"/>
<xsl:element name="grf:messageHeader">
<xsl:element name="grf:messageType">
<xsl:choose>
<xsl:when test="$_commandType = 'api_info'">
<xsl:text>apiInfo</xsl:text>
</xsl:when>
<xsl:when test="$_commandType = 'instrument_status'">
<xsl:text>instrumentStatus</xsl:text>
</xsl:when>
</xsl:choose>
</xsl:element>
</xsl:element>
<xsl:element name="grf:messageBody">
<xsl:choose>
<xsl:when test="$_commandType = 'api_info'">
<xsl:element name="grf:apiInfoBody">
<xsl:element name="grf:apiVersion">
<xsl:value-of select="/message/cmd/api-version"/>
</xsl:element>
<xsl:element name="grf:apiBuild">
<xsl:value-of select="/message/cmd/api-build"/>
</xsl:element>
</xsl:element>
</xsl:when>
<xsl:when test="$_commandType = 'instrument_status'">
<xsl:element name="grf:instrumentStatusBody">
<xsl:element name="grf:statusId">
<xsl:choose>
<xsl:when test="$_statusIdValue = '0'">
<xsl:text>Ready</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '1'">
<xsl:text>Running</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '2'">
<xsl:text>NotReady</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '3'">
<xsl:text>PoweringUp</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '4'">
<xsl:text>PoweringDown</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '5'">
<xsl:text>PoweredUp</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '6'">
<xsl:text>PoweredDown</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '7'">
<xsl:text>Tuning</xsl:text>
</xsl:when>
<xsl:when test="$_statusIdValue = '8'">
<xsl:text>Error</xsl:text>
</xsl:when>
</xsl:choose>
</xsl:element>
</xsl:element>
</xsl:when>
</xsl:choose>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Is there XSLT 1.0 code that will behave the same in both Altova XMLSpy and the MS XSLT processor?
Thanks,
AlarmTripper
One thing to note is that in the template that matches the "message" element, you do this
<xsl:apply-templates select="/message/cmd/#id"/>
This will actually try to match the very first message in the XML relative to the document root, regardless of what message you are currently on. It is not selecting relative to the current node. In your case, it looks like there will only ever be one message, so it won't be an issue here, but it would be in other cases.
It is also probably more common to match on elements, rather than attributes, especially where you want to process child elements of an element. So, you would probably replace the above line with this instead
<xsl:apply-templates select="cmd"/>
Then, for the template that matches it, instead of doing this currently
<xsl:template match="/message/cmd/#id">
You would do this instead
<xsl:template match="cmd">
Next, within this template, you could try replacing your variables with simpler select statements
<xsl:variable name="_commandType" select="#id"/>
<xsl:variable name="_statusIdValue" select="status_id"/>
See if that makes a difference.
You are way over-complicating your transformation. Try this considerably simpler stylesheet:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.company.com/schemas/device/version001"
>
<xsl:output indent="yes" encoding="utf-8" />
<!-- main template / entry point -->
<xsl:template match="message">
<message>
<messageHeader>
<xsl:apply-templates select="cmd" mode="head" />
</messageHeader>
<messageBody>
<xsl:apply-templates select="cmd" mode="body" />
</messageBody>
</message>
</xsl:template>
<!-- header templates -->
<xsl:template match="cmd[#id = 'api_info']" mode="head">
<messageType>apiInfo</messageType>
</xsl:template>
<xsl:template match="cmd[#id = 'instrument_status']" mode="head">
<messageType>instrumentStatus</messageType>
</xsl:template>
<!-- body templates -->
<xsl:template match="cmd[#id = 'api_info']" mode="body">
<apiInfoBody>
<apiVersion><xsl:value-of select="api-version" /></apiVersion>
<apiBuild><xsl:value-of select="api-build" /></apiBuild>
</apiInfoBody>
</xsl:template>
<xsl:template match="cmd[#id = 'instrument_status']" mode="body">
<instrumentStatusBody>
<statusId>
<xsl:choose>
<xsl:when test="status_id = 0">Ready</xsl:when>
<xsl:when test="status_id = 1">Running</xsl:when>
<xsl:when test="status_id = 2">NotReady</xsl:when>
<xsl:when test="status_id = 3">PoweringUp</xsl:when>
<xsl:when test="status_id = 4">PoweringDown</xsl:when>
<xsl:when test="status_id = 5">PoweredUp</xsl:when>
<xsl:when test="status_id = 6">PoweredDown</xsl:when>
<xsl:when test="status_id = 7">Tuning</xsl:when>
<xsl:when test="status_id = 8">Error</xsl:when>
<!-- just in caseā€¦ -->
<xsl:otherwise>
<xsl:text>Unknown status_id: </xsl:text>
<xsl:value-of select="status_id" />
</xsl:otherwise>
</xsl:choose>
</statusId>
</instrumentStatusBody>
</xsl:template>
</xsl:stylesheet>
I got rid of all your seemingly superfluous namespace definitions (add them back as you need them) and put your stylesheet into a default namespace. This means you don't need a 'grf:' prefix on every element anymore, without changing the actual result:
<?xml version="1.0" encoding="utf-8"?>
<message xmlns="http://www.company.com/schemas/device/version001">
<messageHeader>
<messageType>instrumentStatus</messageType>
</messageHeader>
<messageBody>
<instrumentStatusBody>
<statusId>Running</statusId>
</instrumentStatusBody>
</messageBody>
</message>
Note how I use different match expressions and different template modes to output the appropriate elements in the right situations. This way any <xsl:variable> or <xsl:choose> become unnecessary, making for a cleaner and more maintainable stylesheet.
Also, usually there is no need to define <xsl:element> explicitly, unless you want to output elements with dynamic names. In all other cases, you can write the element straight-away.
I'm sorry that I can't say for sure why your stylesheet does not run as intended. It works for me, and it looks okay(ish).
Do not hesitate to ask if any of the above is unclear.
It's been a long time since I've coded up any xslt's but based on what I'm seeing you might be able to change this line:
<xsl:variable name="_statusIdValue" select="/message/cmd/status_id"/>
to
<xsl:variable name="_statusIdValue" select="/message/cmd/status_id/."/>
That should tell it to select the content of the element vs the node itself.
Kind of like when you do a value-of operation and you want the node's text content. you would do the same thing.
For example if you wanted to spit back out the status id number you could use the following:
<xsl:value-of select="/message/cmd/status_id/."/>
OK, I found out that if I use the following line to assign the _statusIdValue variable, then the code will function correctly with the XslCompiledTransform class:
<xsl:variable name="_statusIdValue" select="msxsl:node-set(/message/cmd/*)/text()"/>
This replaces the original line which was:
<xsl:variable name="_statusIdValue" select="/message/cmd/status_id"/>
However, the assignment that works in for the XslCompiledTransform class doesn't work with Altova XMLSpy. Is there a variant of the assignment that will work correctly in both the Altova XMLSpy editor and with the XslCompiledTransform class?
Thanks,
AlarmTripper
This is such terrible coding I'm actually glad it doesn't work in .NET, I suggest you rewrite your stylesheet.
Try this:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:grf="http://www.company.com/schemas/device/version001">
<xsl:template match="message">
<xsl:variable name="commmand-type" select="cmd/#id"/>
<xsl:variable name="status-id" select="cmd/status_id/text()"/>
<grf:message>
<grf:messageHeader>
<grf:messageType>
<xsl:choose>
<xsl:when test="$commmand-type = 'api_info'">apiInfo</xsl:when>
<xsl:when test="$commmand-type = 'instrument_status'">instrumentStatus</xsl:when>
</xsl:choose>
</grf:messageType>
</grf:messageHeader>
<grf:messageBody>
<xsl:choose>
<xsl:when test="$commmand-type = 'api_info'">
<grf:apiInfoBody>
<grf:apiVersion>
<xsl:value-of select="cmd/api-version"/>
</grf:apiVersion>
</grf:apiInfoBody>
<grf:apiBuild>
<xsl:value-of select="cmd/api-build"/>
</grf:apiBuild>
</xsl:when>
<xsl:when test="$commmand-type = 'instrument_status'">
<grf:instrumentStatusBody>
<grf:statusId>
<xsl:choose>
<xsl:when test="$status-id = '0'">Ready</xsl:when>
<xsl:when test="$status-id = '1'">Running</xsl:when>
<xsl:when test="$status-id = '2'">NotReady</xsl:when>
<xsl:when test="$status-id = '3'">PoweringUp</xsl:when>
<xsl:when test="$status-id = '4'">PoweringDown</xsl:when>
<xsl:when test="$status-id = '5'">PoweredUp</xsl:when>
<xsl:when test="$status-id = '6'">PoweredDown</xsl:when>
<xsl:when test="$status-id = '7'">Tuning</xsl:when>
<xsl:when test="$status-id = '8'">Error</xsl:when>
</xsl:choose>
</grf:statusId>
</grf:instrumentStatusBody>
</xsl:when>
</xsl:choose>
</grf:messageBody>
</grf:message>
</xsl:template>
</xsl:stylesheet>
I'm using only one <xsl:template>, you can refactor if you feel it's appropiate.