首页 文章

XSLT 2.0中重复节点结构的XPath选择

提问于
浏览
0

我一直试图解决这个问题 .

XML示例是:

<node>
  <ID>123</ID>
  <work>
    <id>1</id>
    <title>Engineer</title>
    <description>
      <short>short</short>
    </description>
  </work>
  <work>
    <id>2</id>
    <title>Engineer</title>
    <description>
      <short>long</short>
    </description>
  </work>
</node>

XSLT 2.0示例:

<xsl:template name="answers">
    <xsl:for-each select="//description">
        <xsl:choose>
            <xsl:when test="ancestor::node[ID='123']/work[2]/description/short"> 
                //DO NOTHING.
            </xsl:when>
            <otherwise>
                 <description>
                  //CREATE OTHERS
                 </description>
            </otherwise>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>

这里的想法是创建新模板来调用"for-each description"部分 . 但我只想要第一个描述,因为我会在第一个描述中写下第二个描述 . 所以我不需要为第二次描述创建任何东西 . 当它是具有 <short> 节点的第二个描述时,请忽略 . 无法使用值 short='long' 定义解决方案 . 因为语言或值可以更改,但XPath位置将始终相同 .

我得到的结果就是这样

long
long

因此,当我执行代码时,它也会忽略第一个节点,因为它们属于同一个 ID='123' ,我想 . 具有相同 ID 的该组可重复N次 . 如何仅选择第二个 work 节点的 description ,每个重复时间的值为 "long" ,XPath,而不是基于文本值 .

1 回答

  • 0

    据我所知,你想要从子 ID = 123处理每个 nodefirst description .

    它得出一个结论,你有 multiple node 元素,因此由于XML语法要求,它们必须是某个父节点的子节点(我假设它们是直接子节点) .

    要获得所需的值,您可以使用:

    <xsl:value-of select="descendant::description[1]/short"/>
    

    其中 descendant::description[1] 只给出了第一个 description 元素,无论它在XML树中的深度如何 .

    整个脚本可以如下所示:

    <?xml version="1.0" encoding="UTF-8" ?>
    <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
      <xsl:output method="xml" encoding="UTF-8" indent="yes" />
    
      <xsl:template match="root">
        <xsl:copy>
          <xsl:for-each select="node[ID='123']">
            <description>
              <xsl:value-of select="descendant::description[1]/short"/>  
            </description>
          </xsl:for-each>
        </xsl:copy>
      </xsl:template>
    </xsl:transform>
    

    有关工作示例,请参阅http://xsltransform.net/pNvs5wi

    我是"expanded"您的XML源,因此它包含2个 node 元素,我的脚本输出每个源的第一个描述 node .

相关问题