【问题标题】:select a single XML node by the values of multiple of its childnodes通过其多个子节点的值选择单个 XML 节点
【发布时间】:2013-09-29 22:30:47
【问题描述】:

我想通过存在 2 个子节点的值来选择节点,例如给我 objecttype 节点值为 5 且 objectid 节点值为 2 的节点。

objectid 和 objecttype 的组合是唯一的,所以它总是会返回一个结果。

XSL 语句是什么?

<response>
    <result name="response" numFound="5" start="0">
        <doc>
            <str name="title">Tours</str>
            <int name="objecttype">5</int>
            <str name="friendlyurl">tours</str>
            <str name="avatar">2_156_DSC01511.JPG</str>
            <int name="objectid">2</int>
        </doc>
        <doc>
            <str name="title">Celebrations Car</str>
            <int name="objecttype">5</int>
            <str name="friendlyurl">celebrations-car</str>
            <str name="avatar">3_583_0509-0257-20x30-framed.jpg</str>
            <int name="objectid">3</int>
        </doc>
    </result>
</response>

【问题讨论】:

    标签: xml xslt select xmlnode


    【解决方案1】:

    假设您在 $id$type 中有搜索条件。

    如果你有一个小文件:

    /response/result/doc[int[@name='objectid']=$id and int[@name='objecttype']=$type]
    

    如果您有数千个 &lt;doc&gt; 元素:

    <xsl:key name="lookup" match="doc"
             use="concat(int[@name='objectid'],'&#xd;',int[@name='objecttype'])"/>
    
    ...
    
      select="key('lookup',concat($id,'&#xd;',$type))"
    

    这些都适用于 XSLT 1.0 和 XSLT 2.0。

    【讨论】:

    • 我领先你 3 分钟,但添加 xsl:key 示例可以获得奖励积分! :)
    【解决方案2】:

    我假设您想根据其子节点选择doc 节点?如果是这样,鉴于上述 xml 示例,您将必须创建一个 xpath,它基于两个谓词(每个谓词都有自己的谓词)选择 doc。它可能看起来像这样:

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions">
        <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
        <xsl:template match="/">
    
            <xsl:copy-of select="response/result/doc[int[@name='objecttype'] = '5' and int[@name='objectid'] = '2']" />
    
        </xsl:template>
    
    </xsl:stylesheet>
    

    我在本地测试过,输出是:

    <doc>
        <str name="title">Tours</str>
        <int name="objecttype">5</int>
        <str name="friendlyurl">tours</str>
        <str name="avatar">2_156_DSC01511.JPG</str>
        <int name="objectid">2</int>
    </doc>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-10
      • 2018-03-15
      • 2020-12-18
      • 1970-01-01
      相关资源
      最近更新 更多