首页 > 解决方案 > 存在(或不存在)某些属性的复制节点

问题描述

我目前有这个运行良好的 xsl

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="node()">
        <xsl:copy copy-namespaces="no">
            <xsl:copy-of select="@Ccy"/>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

这实质上重写了我的 XML,删除了除 Ccy 之外的所有属性。但是,我现在还需要包含名称为“name”的属性。我想合并我想保留的属性名称:

<xsl:copy-of select="@Ccy | @name"/>

或者,理想情况下,复制所有属性,除了

<xsl:copy-of select="!@BadAttyName"/>

有任何想法吗??

标签: xmlxsltxpathxslt-1.0xslt-2.0

解决方案


您可以使用以下样式表:

输入:

$more input.xml 
<?xml version="1.0"?>
<a>
  <b Ccy="123" name="test1" BadAttyNameTest="toRemove1" BadAttyNameTestt="toRemovee1" other="hey1">toto</b>
  <b Ccy="456" name="test2" BadAttyNameTest="toRemove2" BadAttyNameTestt="toRemovee2" other="hey2">abc</b>
  <b Ccy="789" name="test3" BadAttyNameTest="toRemove3" BadAttyNameTestt="toRemovee3" other="hey3">uvw</b>
</a>

联盟:

::::::::::::::
inputUnion.xsl
::::::::::::::
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="node()">
        <xsl:copy copy-namespaces="no">
            <xsl:copy-of select="@Ccy | @name"/>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

输出联合:

$xsltproc inputUnion.xsl input.xml 
<a>
  <b Ccy="123" name="test1">toto</b>
  <b Ccy="456" name="test2">abc</b>
  <b Ccy="789" name="test3">uvw</b>
</a>

它只会复制属性的并集,@Ccy | @name不考虑其他属性。

除了:

::::::::::::::
inputNOT.xsl
::::::::::::::
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="node()">
        <xsl:copy copy-namespaces="no">
            <xsl:copy-of select="@*[not(starts-with(name(),'BadAttyName'))]"/>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

输出除了:

$xsltproc inputNOT.xsl input.xml 
<a>
  <b Ccy="123" name="test1" other="hey1">toto</b>
  <b Ccy="456" name="test2" other="hey2">abc</b>
  <b Ccy="789" name="test3" other="hey3">uvw</b>
</a>

该语法@*[not(starts-with(name(),'BadAttyName'))]将采用满足括号中条件的所有属性。条件是所有不以 开头的元素BadAttyName,这是通过组合not()and创建的starts-with()


推荐阅读