2009-11-20 93 views
5

我有一個XML文件,我需要刪除一個名爲「Id」的屬性(它必須被刪除,無論它出現在哪裏),我也需要重命名父標籤,同時保持其屬性和子元素不變。你請幫我修改代碼。此時此刻,我只能夠實現兩個要求之一。我的意思是,我可以從文件中完全刪除屬性或我可以改變父標籤.. 這裏是我的代碼,從而消除屬性「ID」:XSLT:如何更改父標記名稱並從XML文件中刪除屬性?

<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    </xsl:template> 
    <xsl:template match="@Id[parent::*]"> 
    </xsl:template> 

請幫我改變父標籤名稱從「根」到「批」。

回答

5

無所提供的解決方案,真正解決了這個問題 :它們只是簡單地重命名一個名爲「Root」的元素(甚至只是t op元素),而不驗證此元素是否具有「Id」屬性。

wwerner是最接近正確的解決方案,而改父父。

這裏是一個具有以下屬性的解決方案:

  • 這是正確的。
  • 它很短。
  • 它是一般化的(替換名稱包含在一個變量中)。

下面是代碼:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:variable name="vRep" select="'Batch'"/> 

    <xsl:template match="node()|@*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*"/> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="@Id"/> 

    <xsl:template match="*[@Id]"> 
    <xsl:element name="{$vRep}"> 
     <xsl:apply-templates select="node()|@*"/> 
    </xsl:element> 
    </xsl:template> 
</xsl:stylesheet> 
+0

哦!你是對的!以及我從來沒有觀察到這一點,實際上在我的實際XML根目錄中從來沒有「id」屬性,所以它一直沒有被觀察到。我真的很感謝你:-)沒有什麼可以否認接受這個答案..: - ) – 2010-02-22 04:55:04

2

我會嘗試:未指定,當您使用

<xsl:template match="@*|node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 
<xsl:template match="@Id"> 
</xsl:template> 
<xsl:template match="/Root"> 
    <Batch> 
    <xsl:apply-templates select="@*|node()"/> 
    </Batch> 
</xsl:template> 

第一塊複製所有。 第二個替換@id與任何地方發生。 第三個將/Root重命名爲/Batch

+0

非常感謝你。 :-) – 2009-11-20 11:43:27

2
<xsl:template match="@*|node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*|node()|text()"/> 
    </xsl:copy> 
</xsl:template> 
<xsl:template match="@Id" /> 
<xsl:template match="Root"> 
    <Batch> 
    <xsl:copy-of select="@*|*|text()" /> 
    </Batch> 
</xsl:template> 
+2

根[@Id]變爲批處理[@Id]而不是被過濾掉。根規則應該應用模板。 – 2009-11-20 10:55:39

+0

而不是 我寫了它能工作.. 你能解釋一下爲什麼xslt的行爲像這個 ? – 2009-11-20 11:54:33

+2

副本將創建所有已選內容的副本,而不考慮現有模板。 apply-templates應用模板。有一個用於@Id的模板,其輸出爲空。 – 2009-11-20 12:04:19

2

這應該做的工作:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
     <xsl:apply-templates select="@*|node()|text()" /> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="node()[node()/@Id]"> 
     <batch> 
     <xsl:apply-templates select='@*|*|text()' /> 
     </batch> 
    </xsl:template> 

    <xsl:template match="@Id"> 
    </xsl:template> 
</xsl:stylesheet> 

我用下面的XML輸入測試:

<root anotherAttribute="1"> 
<a Id="1"/> 
<a Id="2"/> 
<a Id="3" anotherAttribute="1"> 
    <b Id="4"/> 
    <b Id="5"/> 
</a> 

+1

正如我所理解的問題,不僅名稱爲root的標籤應該被重命名,而且所有包含具有Id屬性的元素的父標籤都應該被重命名。 如果這是正確的,簡單地匹配「根」將不會做這項工作。 如果不是,就足以匹配「根」 – wwerner 2009-11-20 10:33:42

+0

非常感謝。 :) – 2009-11-20 11:37:11

相關問題