为何我的XSLT返回空命名空间xmlns=""?如何消除该属性?
解决XSLT转换中空命名空间
xmlns=""问题 问题根源
你创建的<this:First_Name>和<this:Last_Name>元素,虽通过xsl:namespace-alias将this前缀映射为空前缀,但在流式处理的in-memory子模式中,命名空间别名未正确生效。新元素被标记为this对应的命名空间,而输出时无法自动继承父节点的默认命名空间,因此解析器添加xmlns=""明确这些元素不属于当前默认命名空间。
修复方案
方案1:直接创建默认命名空间元素(推荐)
去掉this前缀,直接创建元素,同时通过xpath-default-namespace确保模板匹配和元素创建都使用正确的默认命名空间。
修改后的完整XSLT:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:this="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09" xpath-default-namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09" exclude-result-prefixes="xs this" version="3.0"> <xsl:mode streamable="yes" on-no-match="shallow-copy"/> <xsl:template match="PmtTpInf" > <xsl:apply-templates select="copy-of()" mode="in-memory"/> </xsl:template> <xsl:template match="PmtTpInf" mode="in-memory"> <First_Name>BUSINESS</First_Name> <Last_Name>MAN</Last_Name> </xsl:template> </xsl:stylesheet>
方案2:用xsl:element显式指定命名空间
如果需要保留前缀别名方式,可通过xsl:element明确指定目标命名空间,确保元素属于默认命名空间:
<xsl:template match="this:PmtTpInf" mode="in-memory"> <xsl:element name="First_Name" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"> BUSINESS </xsl:element> <xsl:element name="Last_Name" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"> MAN </xsl:element> </xsl:template>
修复后输出示例
First_Name和Last_Name会继承父节点PmtInf的默认命名空间,不再出现xmlns=""属性:
<?xml version="1.0" encoding="UTF-8"?><Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"> <CstmrCdtTrfInitn> <GrpHdr> <MsgId>15957</MsgId> <CreDtTm>2025-05-14T03:03:11.917-07:00</CreDtTm> <NbOfTxs>3</NbOfTxs> <CtrlSum>30</CtrlSum> <InitgPty> <Nm>GtmtpTest</Nm> </InitgPty> </GrpHdr> <PmtInf> <PmtInfId>159571</PmtInfId> <PmtMtd>TRF</PmtMtd> <BtchBookg>false</BtchBookg> <NbOfTxs>3</NbOfTxs> <CtrlSum>30</CtrlSum> <First_Name>BUSINESS</First_Name><Last_Name>MAN</Last_Name> <ReqdExctnDt> <Dt>2025-05-14</Dt> </ReqdExctnDt> ...
内容的提问来源于stack exchange,提问作者Jack Creed
相关产品推荐
相关产品推荐

