2

I am trying to extract text from XML similar to the following:

<p>This is a paragraph <a href='http://link.com'>with an embedded link</a> with more text afterwards</p>

I would like the extracted text to maintain the URL within the the paragraph, like this:

This is a paragraph with an embedded link (http://link.com) with more text afterwards

It is fairly straight forward to extract the text:

<xsl:value-of select="p"/> and the URL: <xsl:value-of select="p/a/@href"/>, but I am struggling to think of a way to embed the URL within the extracted text using XSLT.

Any ideas on how this can be done?

If there is no easy way to do this I may end up either doing some pre-processing of the text to embed the URL and just use XSLT to extract all the text from there.

1 Answer 1

4
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" indent="yes"/>

  <xsl:template match="/">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:value-of select="."/>
  </xsl:template>

  <xsl:template match="a">
    <xsl:value-of select="."/>

    <xsl:value-of select="concat(' (', @href, ')')"/>
  </xsl:template>

</xsl:stylesheet>

Template <xsl:template match="text()"> matches text nodes and simply outputs them.

Template <xsl:template match="a"> outputs content of a element and its (@href) value.

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

3 Comments

Some explanation of what you are doing would be helpful :D. Do that and you get +1.
Good approach but rough on the edges: it relies on some whitespace being there in the surrounding text nodes -- generally, this maynot be the case.
@DimitreNovatchev True, some of the links may be at the end of sentences or followed by text in a sentence. I'll see if I can get rid of that issue.

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.