非常简单的XSL / XPath健全性检查

时间:2012-08-09 15:59:40

标签: xml xslt xpath

这肯定是一个非常简单的问题。我有一个xml文档,我正在通过XSL进行转换。这个xml的重要部分如下所示:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Transaction>
    <EnrollmentModel>
      <FutureContributionsModel>
        <FutureContributionsElectionType>ACertainThirdParty</FutureContributionsElectionType>
      </FutureContributionsModel>
    </EnrollmentModel>
  <Transaction>
</root>

如果<FutureContributionsElectionType>的值实际上等于ACertainThirdParty,我想添加以下内容:

<fo:table-row>
    <fo:table-cell>
        <fo:block font-family="verdanaPS" font-size="9" padding-bottom="15px" padding-top="10px">
                        The Participant has successfully opted in to use ACertainThirdParty as the managed provider for the account.
        </fo:block>
    </fo:table-cell>
</fo:table-row>

请注意,只有一个第三方,所以我不需要获取自定义文本的节点值,我可以在那里进行硬编码。

如果<FutureContributionsElectionType>的值不等于ACertainThirdParty,我不想添加一大堆其他内容。

以下是我尝试的内容:

所以这似乎是<xsl:choose><xsl:when> / <xsl:otherwise>的工作,对吧? 这就是我得到的:

<xsl:choose>
  <xsl:when test="FutureContributionsModel/FutureContributionsElectionType='ACertainThirdParty'">
    <fo:table-row>
      <fo:table-cell>
        <fo:block font-family="verdanaPS" font-size="9" padding-bottom="15px" padding-top="10px">
                        The Participant has successfully opted in to use ACertainThirdParty as the managed provider for the account.
        </fo:block>
      </fo:table-cell>
    </fo:table-row>
  </xsl:when>
  <xsl:otherwise>
    <fo:table-row>
      <fo:table-cell>
          ...
          Lots of stuff
          ...
      </fo:table-cell>
    </fo:table-row>
  </xsl:otherwise>
</xsl:choose>

但是当我转换它时,其他代码被命中而不是正确的代码(在我的xml中,值确实是ACertainThirdParty。我的猜测是我的问题是我不知道XPath,所以我'我可能认为我可以做我不能做的事情。这里发生了什么?

2 个答案:

答案 0 :(得分:1)

最有可能的情境(当前节点)不是Transaction

您可以使用绝对XPath表达式:

/*/Transaction/EnrollmentModel/FutureContributionsModel/FutureContributionsElectionType='ACertainThirdParty'

好多了,避免使用显式条件 - 使用模板和模板匹配模式

<xsl:template match="FutureContributionsElectionType[.='ACertainThirdParty']">

  <!-- Specific Processing Here  -->
</xsl:template>

<xsl:template match="FutureContributionsElectionType[not(.='ACertainThirdParty')]">

  <!-- Other Specific Processing Here  -->
</xsl:template>

答案 1 :(得分:1)

我不确定这是否有效,因为我不使用XSL,但我看到了3个潜在的问题:

  1. 你的XPath中有一个拼写错误:'FutureContributionElectionType'应该是'FutureContribution s ElectionType'
  2. 目前还不清楚你的XPath是否应该从'FutureContributionsModel开始 '或更早