2014-01-22 35 views
0

我需要查找重复的节点(由ID标识),如果存在此类节点,则需要更新其中一个节点的ID。如果有人能够根据xpath或xsl让我知道如何去做,我会很感激。查找带有重复ID的节点并更改ID

示例XML:

<music> 
    <title id="1"/> 
    <title id="2"/> 
    <title id="1"/> 
</music> 

第一和第三节点具有相同的ID。所以,第三个ID变成了'3'。我需要将其更改为以下:

<music> 
    <title id="1"/> 
    <title id="2"/> 
    <title id="3"/> 
</music> 
+2

* “第一和第三节点具有相同的ID。因此第三的id被改变为 '3'。” *除非有已经*是*的节点ID = 3,在这种情况下,您需要升到ID = 4。但是您可能已经在以前的副本中使用了ID = 4,因此您建议的方式比看起来复杂得多。用连续数字对所有*节点重新编号会不会更简单? –

回答

0

请尝试以下的模板:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0"> 
    <xsl:template match="music"> 
     <xsl:copy> 
      <xsl:for-each select="*"> 
       <xsl:element name="{name()}"> 
        <xsl:attribute name="id"> 
         <xsl:choose> 
          <xsl:when test="preceding::*/@id=current()/@id"> 
           <xsl:value-of select="generate-id()"/> 
          </xsl:when> 
          <xsl:otherwise> 
           <xsl:value-of select="@id"/> 
          </xsl:otherwise> 
         </xsl:choose> 
        </xsl:attribute> 
        <xsl:apply-templates/> 
       </xsl:element> 
      </xsl:for-each> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 
+0

这并不能保证未使用的ID被输出,因为可能已经存在一个ID,该ID等于给定标题元素的'position()'。 –

+0

是的,我同意。我会找到另一种方法,并尽快编辑我的答案。 –

+0

谢谢,ID实际上是一个独特的值,如'a3dvb3'不是序列号。将很感激,如果你可以得到一种方式来创建唯一的ID。 – user1749707

0

通常情况下,一个ID的目的是为了唯一标识元素。如果是这样,那么实际的ID字符串是什么都不重要 - 只要没有重复。

因此,最容易出现问题的方法是对所有title元素进行统一编号,正如@ michael.hor257k所述。这可以使用position()xsl:number来完成。

<?xml version="1.0" encoding="utf-8"?> 

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="/music"> 
     <xsl:copy> 
     <xsl:apply-templates/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="title"> 
     <xsl:copy> 
     <xsl:attribute name="id"> 
      <xsl:number/> 
     </xsl:attribute> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

输出

<?xml version="1.0" encoding="UTF-8"?> 
<music> 
    <title id="1"/> 
    <title id="2"/> 
    <title id="3"/> 
</music>