Reputation: 157
I have the following XML:
<--one or more this-->
<Supplement>
<ID>321
<SupplementType>
<Glass>31DK</Glass>
</SupplementType>
</ID>
</Supplement>
When I use a value-of select of the current element it gives me 32131DK (value of both the "ID" and the "Glass" element)
In my output I would like to get the number value after the "ID" element only (321)
The xml input cannot be changed, as it is as-is from the manufacturer.
My XSLT:
<xsl:element name="ProfileSpecification">
<xsl:for-each select="Supplement/ID">
<xsl:value-of select="."/>
</xsl:for-each> </element>
Output I get:
<ProfileSpecification>32131DK</ProfileSpecification>
Output I want:
<ProfileSpecification>321</ProfileSpecification>
Upvotes: 2
Views: 5193
Reputation: 22617
Your approach does not work because
<xsl:value-of select="."/>
returns the string value of the context element. The string value is the concatenation of all descendant text nodes, not only the immediate children.
You should not simply match /
(I guess you do) and fit all the code inside this single template. Rather, define separate template matches for the elements that are important and use apply-templates
to move through the document.
Do not use for-each
without good reason. The same goes for xsl:element
- do not use it if the element name is statically known, use a literal result element instead.
XML Input
Assuming a well-formed (a single root element) and representative (multiple Supplement
elements, as you state in the question text) input XML document:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Supplement>
<ID>321
<SupplementType>
<Glass>31DK</Glass>
</SupplementType>
</ID>
</Supplement>
<Supplement>
<ID>425
<SupplementType>
<Glass>444d</Glass>
</SupplementType>
</ID>
</Supplement>
</root>
XSLT Stylesheet
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" />
<xsl:template match="/root">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="Supplement">
<ProfileSpecification>
<xsl:value-of select="normalize-space(ID/text()[1])"/>
</ProfileSpecification>
</xsl:template>
</xsl:transform>
XML Output
<?xml version="1.0" encoding="UTF-8"?>
<root>
<ProfileSpecification>321</ProfileSpecification>
<ProfileSpecification>425</ProfileSpecification>
</root>
Upvotes: 4