为什么在此XSLT转换后没有输出?

时间:2017-09-13 14:19:28

标签: xml xslt xslt-1.0

我希望在输出中看到hello,但却没有得到它。

XSL

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:if test="//target">
      <xsl:value-of select="@field"/>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

XML

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="callwithparms - Copy.xslt"?>

<xml>
  <partOne>
    <target field="hello"/>
  </partOne>
  <partTwo>
    <number input="2" find="hello" />
    <number input="2" find="world" />
  </partTwo>
</xml>

2 个答案:

答案 0 :(得分:3)

更改

  <xsl:value-of select="@field"/>

  <xsl:value-of select="//target/@field"/>

(此时上下文节点上没有@field属性,root; if语句不会像原始代码所期望的那样更改上下文节点。)

信用:感谢Daniel Haley更正原始答案,说上下文节点是根元素,它确实是根。

答案 1 :(得分:1)

为什么你不期望这个输出?

因为您的转换将以纯文本形式显示:

  

&#34;匹配 root 并测试文档中是否有<target> ,如果是这种情况,请选择字段属性当前节点&#34;

...仍然是/,而不是<target>正如您所期望的那样。

您的xsl应如下所示:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    <xsl:output method="text"/>

    <!-- work your way thru the doc with matching templates ... -->
    <xsl:template match="/">
        <!-- ... and simply apply-templates -->
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="xml">
        <!-- ... and more ... -->
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="partOne">
        <!-- ... and more ... -->
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="target">
        <!-- until you reach the desired element you need -->
        <xsl:value-of select="@field"/>
    </xsl:template>

    <!-- creating empty templates for elements you like to ignore -->
    <xsl:template match="partTwo" />

</xsl:stylesheet>

如果您可以依赖一系列匹配模板而不是尝试为每个模板或在文档结构中远远或向下扩展元素,那么复杂性开始上升会使事情变得更容易。

相关问题