【问题标题】:xslt: embed xml and access itxslt:嵌入 xml 并访问它
【发布时间】:2018-09-26 14:06:43
【问题描述】:

假设我有这个 XML 文件:

<ErrorCodes>
<ErrorCode = "1" value = "ABC"/>
<ErrorCode = "2" value = "DEF"/>
</ErrorCodes>

我可以将它作为变量添加到我的 XSLT 文件中吗? (我不能只将 XML 保存为文件并在我的 XSLT 中引用它)。 XML 必须内嵌在我的 XSLT 文件中。

是否可以使用 XPATH 访问我的 ErrorCodes XML 并根据我作为输入接收到的 ErrorCode 分配我的 XSLT 变量?

【问题讨论】:

  • 这不是 XML 文件。 ErrorCode 元素的格式不正确。

标签: xml xslt xslt-2.0


【解决方案1】:

答案是“是的,你可以”

你可以像这样定义你的变量(这里不需要父级ErrorCodes

<xsl:variable name="errorCodes">
    <ErrorCode code="1" value="ABC"/>
    <ErrorCode code="2" value="DEF"/>
</xsl:variable>

那你就可以这样访问了

<xsl:value-of select="$errorCodes/ErrorCode[@code='2']/@value" />

或者,像这样定义它:

<xsl:variable name="errorCodes" as="node()*">
    <ErrorCode code="1" value="ABC"/>
    <ErrorCode code="2" value="DEF"/>
</xsl:variable>

然后表达式简化成这样

<xsl:value-of select="$errorCodes[@code='2']/@value" />

您也可以使用xsl:key 访问它。比如……

<xsl:key name="errorCodes" match="ErrorCode" use="@code" />

<xsl:variable name="errorCodes">
  <ErrorCode code="1" value="ABC"/>
  <ErrorCode code="2" value="DEF"/>
</xsl:variable>

<xsl:template match="/">
  <xsl:value-of select="key('errorCodes', '2', $errorCodes)/@value" />
</xsl:template>

【讨论】:

  • 需要注意的是,这假定 XSLT 2.0。在 XSLT 1.0 中,保存 XML 片段的变量称为“结果树片段”,您需要 xx:node-set() 扩展函数使其可查询。
猜你喜欢
  • 1970-01-01
  • 2022-01-02
  • 2012-11-29
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
相关资源
最近更新 更多