Home > Blockchain >  How to select sentences starts with a special character in XSL?
How to select sentences starts with a special character in XSL?

Time:11-14

I have an XML file like the following.

<paper>
    <Question_01>
        <QNo>1a</QNo>
        <Question>What is Semantic Web? </Question>
    </Question_01>
    <Question_01>
        <QNo>1b</QNo>
        <Question>“Web 2.0 applications can be used to increase the profit of a business“ Discuss.</Question>
    </Question_01>
    <Question_01>
        <QNo>1c</QNo>
        <Question>Discuss the advantage of the Extensible Markup Language.</Question>
    </Question_01>
</paper>

I want to select questions that start from 'W', as the QNo - 1a and 1b should be the output XSLT. So that I wrote the following code in XSL.

<xsl:for-each select = "paper/Question_01">
    <xsl:if test = "starts-with(Question, 'W')">
        <li>
            <xsl:value-of select = "Question"/>
        </li>
    </xsl:if>                       
</xsl:for-each>

But it selects only the QNo - 1a. How can I write the XSL code as it selects both QNo - 1a and 1b and also as if the relevant sentence can start with several special characters and whitespace following 'W'? Thank you.

CodePudding user response:

You can use the translate function to get rid of unwanted characters. But you have to list them. Here is an example of the condition for the example given:

starts-with(normalize-space(translate(Question,'“','')), 'W')

So add all unwanted chars to the appropriate parameter of the translate function. This is probably the preferred approach for only a couple of characters. But for a lot of chars a different strategy may fit better (Not necessarily an XSLT-1.0 impl).

You could also simplify the whole code snippet to

<xsl:for-each select = "paper/Question_01[starts-with(normalize-space(translate(Question,'“','')), 'W')]">
    <li>
        <xsl:value-of select = "Question"/>
    </li>
</xsl:for-each>

The output should be the same in both.

CodePudding user response:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:output indent="yes"/>
    <xsl:template match="/">
        <xsl:for-each select = "paper/Question_01">
            <xsl:if test = "starts-with(normalize-space(translate(Question,'“','')), 'W')">
                <li>
                    <xsl:value-of select = "Question"/>
                </li>
            </xsl:if>                       
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
  • Related