【问题标题】:How to remove XML elements based on attribute in XSLT如何根据 XSLT 中的属性删除 XML 元素
【发布时间】:2013-09-22 05:38:30
【问题描述】:

我正在为一些基本的 XSLT 苦苦挣扎。我想从某些 XML 中删除一个元素,具体取决于它是否没有某个属性(在本例中为 PriorValue)。

XML 看起来像这样 XML 不仅限于以下部分,它还有很多其他部分,同样的逻辑也适用于它们。

   <Emp>
       <Personal>
            <First_Name>abc</First_Name>
            <Last_Name>xyz</Last_Name>
            <Gender>1</Gender>
            <Birth_Date PriorValue="1980-08-05">1980-09-05</Birth_Date>
            <Country_of_Birth PriorValue="600">724</Country_of_Birth>
            <Marital_Status PriorValue="0">1</Marital_Status>
        </Personal>
        <Info>
            <Name>abc</Name>
            <ID>Part time</ID>
            <NoOfProbationDays>0</NoOfProbationDays>
            <EMPtype>0</EMPtype>
            <CountryOfBirth PriorValue="IND">ESP</CountryOfBirth>
        </Info>
    </Emp>

所需的 XML 输出如下所示。

    <Emp>
        <Personal>
            <Birth_Date PriorValue="1980-08-05">1980-09-05</Birth_Date>
            <Country_of_Birth PriorValue="600">724</Country_of_Birth>
            <Marital_Status PriorValue="0">1</Marital_Status>
        </Personal>
        <Info>
            <CountryOfBirth PriorValue="IND">ESP</CountryOfBirth>
        </Info>
    </Emp>

感谢您的帮助。

【问题讨论】:

    标签: xml xslt xpath xquery


    【解决方案1】:

    使用

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

    【讨论】:

    • 非常感谢您的回答,另外我如何从中排除几个部分。示例:假设有一个摘要部分,我不想对其应用先验值检查并且总是希望它在输出 XML 中?感谢您的帮助
    • &lt;xsl:template match="*[not(*) and not(@PriorValue)]"/&gt; 更改为&lt;xsl:template match="*[not(self::summary) and not(*) and not(@PriorValue)]"/&gt;。如果您的输入可以包含没有PriorValue 属性的summary 元素,并且您仍然希望将其复制到结果中,那么应该这样做。如果summary 可以是您不想删除它们的其他元素的父级,则使用例如&lt;xsl:template match="*[not(self::summary)]/*[not(*) and not(@PriorValue)]"/&gt;.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多