2

I came across situation where XML tag has HTML code that needs to be parsed in XSLT. Here is the XML sample:

<note>
    <text>&lt;p&gt;This is a paragraph.&lt;/p&gt;&lt;p&gt;This is another paragraph.&lt;/p&gt;</text>
</note>

I want the embedded paragraph elements to be stored in different variables.

This is a paragraph. should be stored in one variable and This is another paragraph. should be stored in another variable.

Can you please help?

2
  • 2
    You can do it in standard XSLT 3 using parse-xml-fragment, see xsltfiddle.liberty-development.net/bFDb2CQ for an example. Expecting to do that in plain XSLT 1.0 in a single step is audacious, unless you have an XSLT 1.0 processor that supports an extension or easily allows you to implement one having access to an (X)HTML parser. Commented Sep 27, 2018 at 11:11
  • Thanks a lot! That's what I was looking for. I changed the tag from xslt-1.0 to xslt-3.0 You can post it as an answer Commented Sep 28, 2018 at 3:39

1 Answer 1

2

Parsing XML documents with parse-xml https://www.w3.org/TR/xpath-functions/#func-parse-xml or XML fragments with parse-xml-fragment https://www.w3.org/TR/xpath-functions/#func-parse-xml-fragment is supported in XSLT 3.0, in earlier versions you would have to rely on processor specific extension provided or implementable.

Your escaped code looks like an XHTML fragment so it should be parseable with parse-xml-fragment as in https://xsltfiddle.liberty-development.net/bFDb2CQ which does

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:output method="html" indent="yes" html-version="5"/>

  <xsl:template match="text">
      <div>
          <xsl:variable name="contents" select="parse-xml-fragment(.)"/>
          <xsl:variable name="p1" select="$contents/p[1]"/>
          <xsl:variable name="p2" select="$contents/p[2]"/>
          <xsl:sequence select="$p1, $p2"/>
      </div>
  </xsl:template>

</xsl:stylesheet>
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.