加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – XSLT:在XSLT中创建一个地图

发布时间:2020-12-16 08:01:43 所属栏目:百科 来源:网络整理
导读:我想在xsl中有一个键值映射,所以定义了一个具有xml片段的变量,但是后来当我尝试访问变量中的xml节点时,我得到一个错误,类型的xpath xpression无法解析。 xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:template m
我想在xsl中有一个键值映射,所以定义了一个具有xml片段的变量,但是后来当我尝试访问变量中的xml节点时,我得到一个错误,类型的xpath xpression无法解析。
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:variable name="map">
            <map>
                <entry key="key-1">value1</entry>
                <entry key="key-2">value2</entry>
                <entry key="key-3">value3</entry>
            </map>
        </xsl:variable>
        <output>
            <xsl:value-of select="$map/entry[@key='key-1']"/>
        </output>
    </xsl:template>
</xsl:stylesheet>
XSLT 2.0

使用XSLT 2.0,以下解决方案的工作原理是:

<xsl:variable name="map">
    <entry key="key-1">value1</entry>
    <entry key="key-2">value2</entry>
    <entry key="key-3">value3</entry>
  </xsl:variable>

  <xsl:template match="/">
    <output>
      <xsl:value-of select="$map/entry[@key='key-1']"/>
    </output>
  </xsl:template>

XSLT 1.0

您不能在XSLT 1.0中的XPath表达式中使用结果树片段,但是fn:document()可以检索映射值。一个similar question的答案将在这里工作:

<xsl:value-of select="document('')//xsl:variable[@name='map']/map/entry[@key='key-1']"/>

如XSLT 1.0 specification年所述:

document("") refers to the root node of
the stylesheet; the tree
representation of the stylesheet is
exactly the same as if the XML
document containing the stylesheet was
the initial source document.

但是,您不需要为此使用xsl:variable。您可以直接在xsl:stylesheet下指定地图节点,但您必须记住,顶级元素必须具有非空名称空间URI:

<xsl:stylesheet 
  version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:my="some.uri" exclude-result-prefixes="my">

  <my:map>
    <entry key="key-1">value1</entry>
    <entry key="key-2">value2</entry>
    <entry key="key-3">value3</entry>
  </my:map>

  <xsl:template match="/">
    <output>
      <xsl:value-of select="document('')/*/my:map/entry[@key='key-1']"/>
    </output>
  </xsl:template>
</xsl:stylesheet>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读