首页 > 解决方案 > 使用 xslt 过滤特定的 XML 节点

问题描述

我想使用 XSLT 从我的 XML 输入中过滤<end_date/>元素。我尝试了不同的方法,但似乎不起作用。你能建议我如何实现吗

样本有效载荷:

<?xml version="1.0" encoding="UTF-8"?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <version_id>2005P0</version_id>
        <person>
            <person_id_external>484284</person_id_external>
            <employment_information>
                <employment_id>864</employment_id>
                <end_date/>
            </employment_information>
        </person>
        <person>
            <person_id_external>484285</person_id_external>
            <employment_information>
                <employment_id>865</employment_id>
                <end_date>2020-12-31</end_date>
            </employment_information>
        </person>
        <person>
            <person_id_external>484286</person_id_external>
            <employment_information>
                <employment_id>866</employment_id>
                <end_date>2021-02-01</end_date>
            </employment_information>
        </person>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>

预期输出(要为 person_id_external 484284 删除的元素):

<?xml version="1.0" encoding="UTF-8"?>
<queryCompoundEmployeeResponse>
    <CompoundEmployee>
        <version_id>2005P0</version_id>
        <person>
            <person_id_external>484284</person_id_external>
            <employment_information>
                <employment_id>864</employment_id><end_date/>
            </employment_information>
        </person>
        <person>
            <person_id_external>484285</person_id_external>
            <employment_information>
                <employment_id>865</employment_id>
                <end_date>2020-12-31</end_date>
            </employment_information>
        </person>
        <person>
            <person_id_external>484286</person_id_external>
            <employment_information>
                <employment_id>866</employment_id>
                <end_date>2021-02-01</end_date>
            </employment_information>
        </person>
    </CompoundEmployee>
</queryCompoundEmployeeResponse>

XSL 我试过:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 

 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 
 <xsl:template match="//CompoundEmployee/person/employment_information/end_date[not(end_date)]"/>
 
 </xsl:stylesheet>

标签: xmlxslt

解决方案


删除任何空白的模板end_date将只是一个 empty <xsl:template match="end_date[not(node())]"/>


推荐阅读