XSLT:如何更改父标记名称并从XML文件中删除属性?
我有一个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>
请帮我改变父标签名称从“根”到“批”。
无所提供的解决方案,真正解决了这个问题 :它们只是简单地重命名一个名为“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>
我会尝试:未指定,当您使用
<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
。
非常感谢你。 :-) – 2009-11-20 11:43:27
<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>
根[@Id]变为批处理[@Id]而不是被过滤掉。根规则应该应用模板。 – 2009-11-20 10:55:39
而不是
副本将创建所有已选内容的副本,而不考虑现有模板。 apply-templates应用模板。有一个用于@Id的模板,其输出为空。 – 2009-11-20 12:04:19
这应该做的工作:
<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>
正如我所理解的问题,不仅名称为root的标签应该被重命名,而且所有包含具有Id属性的元素的父标签都应该被重命名。 如果这是正确的,简单地匹配“根”将不会做这项工作。 如果不是,就足以匹配“根” – wwerner 2009-11-20 10:33:42
非常感谢。 :) – 2009-11-20 11:37:11
哦!你是对的!以及我从来没有观察到这一点,实际上在我的实际XML根目录中从来没有“id”属性,所以它一直没有被观察到。我真的很感谢你:-)没有什么可以否认接受这个答案..: - ) – 2010-02-22 04:55:04