【问题标题】:How to get same element 2nd time came in same parent element如何第二次获得相同的元素进入相同的父元素
【发布时间】:2017-01-10 09:55:33
【问题描述】:

我需要使用 xslt 在同一个父元素中第二次选择同一个元素。

我正在显示我的 xml..

<parent>
            <a>0001</a>
            <b>05</b>
            <c>20160825</c>
            <d>9463</d>
            <e>anders skov petersen</e>
            <f></f>
            <g></g>
            <h></h>
            <i></i>
            <a>0002</a>
            <b>05</b>
            <c>20160825</c>
            <d>9463</d>
            <e>anders skov petersen</e>
            <f></f>
            <g></g>
            <h></h>
            <i></i>
        </parent>

在我的 xml 中,a、b、c 和所有其他元素都出现了两次。因此,如果我必须在 XSLT 中获取第二次出现的元素的值,那么任何人都可以告诉我该怎么做吗?

【问题讨论】:

  • 您是否仅根据元素名称查找重复项?还是关于元素内容?是否可以有复杂的内容,例如&lt;j&gt;&lt;foo&gt;bar&lt;/foo&gt;&lt;/j&gt;?

标签: xml xslt xsd xslt-1.0


【解决方案1】:

您可以使用以下 XPath-Expression 访问第二个 a

/parent/a[2]

这是的缩写形式

/parent/a[position()=2]

https://www.w3.org/TR/xpath/

【讨论】:

    【解决方案2】:

    试试这个来识别在同一个父元素中出现两次的相同元素(名称,而不是内容):

    输入 XML:

    <parent>
       <a>0001</a>
       <b>05</b>
       <c>20160825</c>
       <d>9463</d>
       <e>anders skov petersen</e>
       <f></f>
       <g></g>
       <h></h>
       <i></i>
       <a>0002</a>
       <b>05</b>
       <c>20160825</c>
       <d>9463</d>
       <e>anders skov petersen</e>
       <f></f>
       <g></g>
       <h></h>
       <i></i>
       <j>New element</j>
    </parent>
    

    XSLT 1.0:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
    
    <xsl:key name="kDuplicate" match="*[generate-id(parent::*) = 
                                     generate-id(current()/parent::*)]" use="name()"/>
    
    <xsl:template match="@*|node()">
        <xsl:copy>
          <xsl:apply-templates select="@*|node()[key('kDuplicate', name())[2]]"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="parent">
        <xsl:copy>
          <xsl:for-each select="descendant::*[key('kDuplicate', name())[2]]">
            <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
          </xsl:for-each>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    

    结果:(元素j 没有出现,因为它只在其父元素中出现过一次)

    <parent>
      <a>0001</a>
      <b>05</b>
      <c>20160825</c>
      <d>9463</d>
      <e>anders skov petersen</e>
      <f/>
      <g/>
      <h/>
      <i/>
      <a>0002</a>
      <b>05</b>
      <c>20160825</c>
      <d>9463</d>
      <e>anders skov petersen</e>
      <f/>
      <g/>
      <h/>
      <i/>
    </parent>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      相关资源
      最近更新 更多