使用XLST从xml文件中删除元素

时间:2016-07-02 12:13:33

标签: xml web-services xslt soap

我正在尝试从XML格式的soap响应中删除某些元素。但是,当我使用其他XLST问题中的建议时,我总是最终删除嵌套在元素中的所有内容。我只想省略xml文档的那一部分,这样我就可以拥有一个没有名称空间或肥皂信封等的干净XML文档。

我试图使用这样的想法:remove xml tags with XSLT

但没有运气。如果有人能帮助我实现这一目标,那真的很棒。

示例XML:

<?xml version="1.0" encoding="UTF-8"?>
<request_dataResponse encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><request_dataReturn type="soapenc:string"><Vessel>
  <VesselID>117774</VesselID>
  <IMO>7625988</IMO>
  <VslName>Shamrock Pride</VslName>
</Vessel>
</request_dataReturn></request_dataResponse>

请注意,由于某种原因,容器标签不在下一行,而是位于soap标签的末尾。在这一行中还有多个名为Request和Return的soap标签。

我希望实现的是这样的XML:

<?xml version="1.0" encoding="UTF-8"?>
<Vessel>
  <VesselID>117774</VesselID>
  <IMO>7625988</IMO>
  <VslName>Shamrock Pride</VslName>
</Vessel>

我尝试过如下使用XSLT:

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

但它只是删除嵌套在soap标签后面的标签中的所有数据。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

我只是在这里猜测,因为您的输入不是XML文档,但要删除包装元素并保留其后代,您必须这样做:

<xsl:template match="wrapper">
   <xsl:apply-templates/>
</xsl:template>

就是说,在你的情况下:

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

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

<xsl:template match="request_dataResponse | request_dataReturn">
    <xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>

您现在拥有的处理根request_dataResponse元素并停在那里。