how to escape single quote in xslt substring funct

2019-01-07 23:21发布

I tried to substring data with single quote in XSLT:

String : DataFromXML:'12345'

expected Result: 12345

<xsl:value-of select="substring-after('$datafromxml','DataFromXML:')"/>

Result: '12345'

i tried below code

<xsl:value-of select="substring-after('$datafromxml','DataFromXML:&#39;')"/>

<xsl:value-of select="substring-after('$datafromxml','DataFromXML:&apos;')"/>

<xsl:value-of select="substring-after('$datafromxml','DataFromXML:'')"/>

Error:

String literal was not closed 'DataFromXML:'--->'<---

标签: xslt xpath
4条回答
不美不萌又怎样
2楼-- · 2019-01-07 23:52

The general rules for escaping are:

In 1.0:

  • if you want the attribute delimiter in a string literal, use the XML escape form &quot; or &apos;
  • if you want the string delimiter in a string literal, you're hosed

In 2.0:

  • if you want the attribute delimiter in a string literal, use the XML escape form &quot; or &apos;
  • if you want the string delimiter in a string literal, double it (for example, 'I can''t')

The use of a variable $quot or $apos as shown by Vitaliy can make the code much clearer.

查看更多
祖国的老花朵
3楼-- · 2019-01-08 00:02

Even in the most complicated case -- the string contains both a quote and an apostrophe -- the number can be extracted without resorting to variables.

Suppose we have this XML document:

<t>' "12345' "</t>

and want to extruct just the number.

In the following transformation we use a single XPath expression to do exactly that:

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

 <xsl:template match="text()">
     <xsl:value-of select=
     'substring-after(.,"&apos;")
     '/>
==============  
     <xsl:value-of select=
     'substring-before(
       substring-after(substring-after(.,"&apos;"), &apos;&quot;&apos;),
       "&apos;"
                       )
     '/>
 </xsl:template>
</xsl:stylesheet>

The result is:

 "12345' "
==============  
     12345

Do note: I am intentionally having two XPath expressions -- the purpose of the first one is to make it simpler to understand what is expressed in the second XPath expression. Leaving just the last xsl:value-of in the template body produces exactly the wanted result:

12345
查看更多
相关推荐>>
4楼-- · 2019-01-08 00:03

This should work:

<xsl:variable name="apos">'</xsl:variable>

...

<xsl:value-of select="substring-before(substring-after($datafromxml, concat('DataFromXML:', $apos)), $apos)" />
查看更多
虎瘦雄心在
5楼-- · 2019-01-08 00:05

You could try swapping and " and ' in your xsl:value-of

<xsl:value-of select='substring-before
   (substring-after($datafromxml,"DataFromXML:&apos;"), "&apos;")'/> 

Alternatively, you could make use of the translate function to remove the pesky apostrophes

 <xsl:value-of select='translate
    (substring-after($datafromxml,"DataFromXML:"), "&apos;", "")'/> 

Not necessarily nicer, but it does remove the need for a variable.

查看更多
登录 后发表回答