用变量替换XSLT的内容

时间:2017-07-10 06:47:59

标签: xml xslt

我想用预定义的变量替换文件路径。

路径变量的来源(只有两个例子 - 在期望的结果中它会更多):

<xsl:variable name='fileA'>
   <xsl:text>C:\\example\\fileA.xml</xsl:text>
</xsl:variable>

<xsl:variable name='fileB'>
  <xsl:text>C:\\example\\fileB.xml</xsl:text>
</xsl:variable>

包含路径的代码的来源:

<topic insetPath="C:\\example\\fileA.xml" flowTag="title"/>
<topic insetPath="C:\\example\\fileB.xml" flowTag="text"/>    

所需的XML输出:

<topic flowTag="title"><xsl:attribute name="insetPath"><xsl:value-of select="$fileA"/></xsl:attribute></topic>
<topic flowTag="text"><xsl:attribute name="insetPath"><xsl:value-of select="$fileB"/></xsl:attribute>

我的变量xsl看起来像这样:

<xsl:stylesheet>
  <xsl:variable name='fileA'>
    <xsl:text>C:\\example\\fileA.xml</xsl:text> 
  </xsl:variable>

  <xsl:variable name='fileB'>
    <xsl:text>C:\\example\\fileB.xml</xsl:text> 
 </xsl:variable>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:0)

我不确定你应该使用(纯)XSLT,因为XSLT缺少允许良好运行时复杂性的容器,但代码很简单:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- Load the variables from a separate XML file.
       Note that this "xsl:" refers to the alias in *this* document, regardless of what alias, if any, is used in varaibles.xml -->
  <xsl:variable name="variables" select="document('variables.xml')/*/xsl:variable/xsl:text/text()"/>
  <!-- Simple modification of the identity transform -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <!-- Must emit attributes first, then elements afterwards. Thus, WET. -->
      <xsl:apply-templates select="@*[not(.=$variables)]"/>
      <xsl:for-each select="@*[.=$variables]">
        <xsl:variable name="attr" select="string(.)"/>
        <!-- Outputting XSLT itself is slightly painful -->
        <xsl:element namespace="http://www.w3.org/1999/XSL/Transform" name="attribute">
          <xsl:attribute name="name">
            <xsl:value-of select="name()"/>
          </xsl:attribute>
          <xsl:element namespace="http://www.w3.org/1999/XSL/Transform" name="value-of">
            <xsl:attribute name="select">
              <xsl:text>$</xsl:text>
              <!-- go up from the text() node, to the xsl:text element, to the xsl:variable element -->
              <xsl:value-of select="$variables[.=$attr]/../../@name"/>
            </xsl:attribute>
          </xsl:element>
        </xsl:element>
      </xsl:for-each>
      <xsl:apply-templates select="node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>