0

if i'm trying to understand xslt where i'm stuck at a place where i want to add an element with a fixed value and a dynamic attribute

input:

<newsItem parentGUID="fakeGuid">
</newsItem>

desired output:

<newsItem>
  <parent Key="fakeGuid">News</parent>
<newsItem>

Current Xslt (value isn't in the actual output)

<xsl:template match="NewsItem">
  <xsl:element name="Parent">
      <xsl:attribute name="Key">
        <xsl:value-of select="@parentGUID"/>
      </xsl:attribute>
      <xsl:value-of select="News"/>
  </xsl:element>
</xsl:template>

Can someone point me out what i'm doing wrong?

Kind regards

2
  • A general comment: If you want to create an element named Parent and that is statically known, just use <parent> instead of <xsl:element name="parent"> (unless you just really like typing and making the XSLT harder to read). Generally, the only time to use xsl:element is if the name is dynamically constructed. Commented May 27, 2020 at 18:45
  • Note that XML is case-sensitive: <xsl:template match="NewsItem"> will NOT match <newsItem>. Commented May 27, 2020 at 18:50

1 Answer 1

1

The instruction:

<xsl:value-of select="News"/>

looks for a child element named News to extract its string-value. To output the literal text "News", try:

<xsl:text>News</xsl:text>

Note also that you don't need to use xsl:element to create a literal result element. To get the result you show, you could do:

<xsl:template match="newsItem">
    <xsl:copy>
        <Parent key="{@parentGUID}">News</Parent>
    </xsl:copy>
</xsl:template>

Read about attribute value templates to understand how this works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.