1

I'm trying to get XSLT to transform something like

<foo>
    lorem ipsum
    <br />
    some more lorem ipsum
</foo>

into

<p>
    lorem ipsum
    <br />
    some more lorem ipsum
</p>

I've tried countless paths for the select attribute of

<p><xsl:value-of select="/foo/*" /></p>

But none of them seemed to work. Is it even possible to get all the children of an element as plain text?

2 Answers 2

3

You can use xsl:copy-of:

<p><xsl:copy-of select="/foo/node()" /></p>

But a preferable approach would be to add an identity template to your XSLT:

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()" />
  </xsl:copy>
</xsl:template>

And then make use of that:

<p><xsl:apply-templates select="/foo/node()" /></p>
Sign up to request clarification or add additional context in comments.

3 Comments

Could you clarify why the xsl:template method is preferable? IF both methods have the same result, isn't the shortest method prefered?
XSLT is a templating language, and the preferred way to use it is to use copy-ofs and procedural-style constructs, and rather use a push-style programming style, allowing the XSLT to be run through templates, which might pick up and operate on different parts. Suppose that somewhere down the road you wanted this XSLT to convert any <b>s in the XML to <strong>s. The apply-templates approach would allow you to do that easily, but the copy-of approach would not allow you to do it at all.
In this portion of my comment "the preferred way to use it is to use copy-ofs and procedural-style constructs", I meant to say "the preferred way to use it is to avoid copy-ofs and procedural-style constructs".
0

Let me know if the following works for you:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">  
  <xsl:for-each select="item/foo">
    <p>
      <xsl:value-of select="current()"/>
    </p>    
  </xsl:for-each> 
</xsl:template>
</xsl:stylesheet>

Tested with this XML:

<?xml version="1.0" encoding="ISO-8859-1"?>
<item>
<foo>
    lorem ipsum
    <br />
    some more lorem ipsum
</foo>
<foo>
    lorem ipsum
    <br />
    some more lorem ipsum
</foo>
</item>

2 Comments

I guess that would work, but the tag <foo> won't be repeated in the XML file, so it seems kind of redundant to write an xsl:for-each for a single node.
This approach would eliminate the <br/> elements (and any other elements that might be within the foos.

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.