XSLT用文本和节点数组替换字符串

时间:2018-07-04 11:49:15

标签: xml xslt

假设我有以下XML输入:

<?xml version="1.0"?>
<root>
  <urls>
    <url>http://foo</url>
    <url>http://bar</url>
  </urls>
  <resources lang="en-US">
    <resourceString id='url-fmt'>See URL: {0}</resourceString>
  </resources>
</root>

我想用XSL生成以下输出(可以使用1.0、2.0甚至3.0):

<?xml version="1.0"?>
<body>
  <p>See URL: <a href="http://foo">http://foo</a></p>
  <p>See URL: <a href="http://bar">http://bar</a></p>
</body>

我有以下XSL样式表存根,但是我很难找到合适的函数来标记资源字符串,提取{0}并将其替换为节点。 replace()似乎没有帮助,因为它仅适用于字符串:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0">
  <xsl:variable name="urlResString"
                select="/root/resources/resourceString[@id='url-fmt']" />
  <xsl:template match="/">
    <body>
      <xsl:apply-templates select="/root/urls/url" />
    </body>
  </xsl:template>
  <xsl:template match="url">
    <p>
      <xsl:variable name='linkToInsert'>
        <a href='{.}'><xsl:value-of select='.'/></a>
      </xsl:variable>
      <xsl:value-of
           select="replace($urlResString, '\{0}', $linkToInsert)" />
    </p>
  </xsl:template>
</xsl:stylesheet>

这里生成的是:

<?xml version="1.0"?>
<body>
  <p>See URL: http://foo</p>
  <p>See URL: http://bar</p>
</body>

如果您可以指导我正确使用功能,那就太好了。

注意:我可能必须对同时具有{0}{1}等的字符串执行此操作,就像.NET中的格式字符串函数一样。

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以按以下方式使用xsl:analyze-string

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:variable name="urlResString"
        select="/root/resources/resourceString[@id='url-fmt']" />
    <xsl:template match="/">
        <body>
            <xsl:apply-templates select="/root/urls/url" />
        </body>
    </xsl:template>
    <xsl:template match="url">
        <p>
            <xsl:variable name='linkToInsert'>
                <a href='{.}'><xsl:value-of select='.'/></a>
            </xsl:variable>
            <xsl:analyze-string select="$urlResString" regex="\{{\d\}}">
                <xsl:matching-substring>
                    <xsl:copy-of select="$linkToInsert"/>
                </xsl:matching-substring>
                <xsl:non-matching-substring>
                    <xsl:copy/>
                </xsl:non-matching-substring>
            </xsl:analyze-string>
        </p>
    </xsl:template>
</xsl:stylesheet>

答案 1 :(得分:1)

 <xsl:template match="root/urls">
        <body>
        <xsl:for-each select="url">
            <p>
                <xsl:value-of select=" substring-before(parent::urls/following-sibling::resources/resourceString,' {')"/><xsl:text> </xsl:text>
                <a href="{.}"><xsl:value-of select="."/></a>
            </p>
        </xsl:for-each>
        </body>
    </xsl:template>
    <xsl:template match="resources"/>
Try it