如何用XSLT移除SOAP信封及命名空间并处理SOAP Body
修正XSLT以移除SOAP信封与命名空间
示例输入XML
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://example.com/temp" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <tem:Data> <Name>Test</Name> <Value>123</Value> </tem:Data> </soap:Body> </soap:Envelope>
修正后的XSLT代码
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://example.com/temp"> <!-- 输出格式化XML,移除不必要的命名空间声明 --> <xsl:output method="xml" indent="yes" omit-xml-declaration="no"/> <!-- 直接跳过SOAP信封,定位到Body内的目标Data节点 --> <xsl:template match="/soap:Envelope"> <xsl:apply-templates select="soap:Body/tem:Data"/> </xsl:template> <!-- 将带命名空间的tem:Data转为无命名空间的Data节点 --> <xsl:template match="tem:Data"> <Data> <xsl:apply-templates select="@*|node()"/> </Data> </xsl:template> <!-- 移除所有元素的命名空间前缀 --> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <!-- 移除所有属性的命名空间前缀 --> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> <!-- 保留文本、注释、处理指令等非元素内容 --> <xsl:template match="text()|comment()|processing-instruction()"> <xsl:copy/> </xsl:template> </xsl:stylesheet>
关键修正点
- 直接匹配根节点
soap:Envelope,只处理内部的soap:Body/tem:Data,彻底跳过Envelope和Body节点,避免它们出现在输出中。 - 专门处理
tem:Data节点,生成无命名空间的<Data>作为根节点,符合输出要求。 - 通用模板通过
local-name()提取节点的本地名称,完全移除所有命名空间前缀,确保输出节点不带任何命名空间。
期望输出
<?xml version="1.0" encoding="UTF-8"?> <Data> <Name>Test</Name> <Value>123</Value> </Data>
内容的提问来源于stack exchange,提问作者Itachi Uchiha
相关产品推荐
相关产品推荐

