如何从XSL 3.0映射获取字符串

问题描述

我有XSL地图

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE stylesheet>
<xsl:stylesheet version="3.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    xmlns:functx="http://www.functx.com"  
    xmlns:map="http://www.w3.org/2005/xpath-functions/map">
    
    <xsl:param name="settings" select="'https://testurl.com' ||  '/_resources/includes/settings.xml'"/>
    
    <xsl:template name="sidenav">
        <map key="style" xmlns="http://www.w3.org/2005/xpath-functions">
            <xsl:choose>
                <xsl:when test="doc-available($settings)">
                    <string key="navcss" select="doc($settings)/document/settings/ouc:div[@label='section-menu-type']"/>
                </xsl:when>
                <xsl:otherwise>
                    <string key="navcss" select="$nav-css"/>
                </xsl:otherwise>
            </xsl:choose>
        </map>
        "style" : <xsl:value-of select="map:get('style')('navcss')"/>
    </xsl:template>
    <xsl:call-template name="sidenav"/>
</xsl:stylesheet>

当我尝试使用以下代码获取值时,我得到:“致命错误:未知类型映射”

"style" : <xsl:value-of select="map:get('style')('navcss')"/>

如果我用这个代替它:

<xsl:variable name="map" select="map {
    'navcss' : if(doc-available($settings)) then doc($settings)/document/settings/ouc:div[@label='section-menu-type'] else 'd3',}"/>
<xsl:value-of select="map:get($map,'navcss')"/>

我得到了价值。我的问题是,您可以创建一个map元素并获取类似于map函数的键,还是只需要使用map xpath函数

解决方法

XSLT 3.0和XPath 3.1中定义的JSON的XML表示使用这样的map元素表示JSON对象,您可以使用xml-to-json将此类XML转换为JSON并将其提供给{{1} };另一方面,要在XSLT 3.0中创建地图,我建议使用parse-jsonxsl:map元素,或者简单地使用XPath 3.1表达式:

xsl:map-entry

对于您在评论中的表达方式,看来您可以使用例如

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:map="http://www.w3.org/2005/xpath-functions/map"
    xmlns:math="http://www.w3.org/2005/xpath-functions/math"
    exclude-result-prefixes="#all"
    expand-text="yes"
    version="3.0">
    
  <xsl:param name="json-xml">
      <map xmlns="http://www.w3.org/2005/xpath-functions">
          <string key="foo">bar</string>
          <number key="pi">3.1415927</number>
      </map>
  </xsl:param>
  
  <xsl:variable name="map1" select="xml-to-json($json-xml) => parse-json()"/>
  
  <xsl:param name="map2" as="map(*)">
      <xsl:map>
          <xsl:map-entry key="'foo'" select="'bar'"/>
          <xsl:map-entry key="'pi'" select="math:pi()"/>
      </xsl:map>
  </xsl:param>
  
  <xsl:template match="root">
      <section>
          <h2>Example</h2>
          <p>{$map1?pi}</p>
          <p>{$map1?foo}</p>
      </section>
      <section>
          <h2>Example</h2>
          <p>{$map2?pi}</p>
          <p>{$map2?foo}</p>
      </section>
  </xsl:template>

我还没有说明所有地图属性,但我希望能清楚地列出那里的其他属性。