代码之家  ›  专栏  ›  技术社区  ›  Amandasaurus

xslt-匹配的节点,其中包含某个节点(如jquery“:has”)。

  •  2
  • Amandasaurus  · 技术社区  · 16 年前

    假设我有以下XML文件

    <a id="123">
       <b type="foo" value="1" />
       <b type="baz" value="1" />
    </a>
    <a id="789">
      <b type="bar" value="12" />
    </a>
    <a id="999">
       <b type="foo", value="2" />
    </a>
    

    我想得到所有“A”节点的列表,这些“A”节点有一个子节点“B”,其类型为“foo”,值为“1”。您可以在jquery中使用“:has”选择器执行类似的操作。

    据我所知,我计划在命令行上使用xmlstarlet(但我并没有打算这样做),所以这样工作的XSLT最好。

    4 回复  |  直到 16 年前
        1
  •  6
  •   gizmo    16 年前

    像这样:

    a[b[@type='foo'][@value='1']]
    

    应该做这个把戏

        2
  •  2
  •   Dimitre Novatchev    16 年前

    这可以使用Gizmo答案中指出的单个xpath表达式来完成。

    因为这个问题是专门针对XSLT的, 这里有一个有效的XSLT解决方案 使用按键:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes"/>
    <!--                                      --> 
     <xsl:key name="kAByBTypeVal" 
      match="a"
      use="concat(b/@type,'+',b/@value)"/>
    <!--                                      -->       
        <xsl:template match="/">
          <xsl:copy-of select=
           "key('kAByBTypeVal', 'bar+12')"/>
        </xsl:template>
    </xsl:stylesheet>
    

    当上述转换应用于此XML文档时 :

    <t>
        <a id="123">
            <b type="foo" value="1" />
            <b type="baz" value="1" />
        </a>
        <a id="789">
            <b type="bar" value="12" />
        </a>
        <a id="999">
            <b type="foo" value="2" />
        </a>
    </t>
    

    产生正确的结果 :

    <a id="789">
      <b type="bar" value="12"/>
    </a>
    
        3
  •  0
  •   Maurice Perry    16 年前

    我想应该是:/b[@type='foo'和@value=1]/parent::a

        4
  •  -1
  •   Nick Allen    16 年前
    <xsl:variable name="nodeList" select="a[b[@type='foo' and @value=1]]"/>
    
    <xsl:for-each select="$nodeList">
        <xsl:value-of select="."/>
    </xsl:for-each>