You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript使用正则移除XML/SOAP报文命名空间前缀的方法

移除SOAP XML报文所有标签的命名空间前缀

需求说明

  • 现有一份SOAP格式XML报文,需要移除所有标签的命名空间前缀
  • 实际业务中命名空间前缀是动态变化的,示例中前缀为s和ans
  • 标签上的xmlns命名空间声明属性需要保留,不需要移除

原始XML内容

const xmlStr = `    <s:Envelope
        xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" 
        xmlns:ans="http://www.ans.gov.br/padroes/tiss/schemas">
        <s:Body>
            <ans:respostaElegibilidadeWS>
                <ans:cabecalho>
                    <ans:identificacaoTransacao>
                        <ans:tipoTransacao>SITUACAO_ELEGIBILIDADE</ans:tipoTransacao>
                    </ans:identificacaoTransacao>
                </ans:cabecalho>
            </ans:respostaElegibilidadeWS>
        </s:Body>
    </s:Envelope>`

期望输出结果

<Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" 
    xmlns:ans="http://www.ans.gov.br/padroes/tiss/schemas">
    <Body>
        <respostaElegibilidadeWS>
            <cabecalho>
                <identificacaoTransacao>
                    <tipoTransacao>SITUACAO_ELEGIBILIDADE</tipoTransacao>
                </identificacaoTransacao>
            </cabecalho>
        </respostaElegibilidadeWS>
    </Body>
</Envelope>

原有错误实现

原有正则逻辑冗余、匹配规则不全,无法正确保留属性、适配所有动态前缀:

xmlStr = xmlStr.replace(/<(\/?)\w+:(\w+\/?) ?(\w+:\w+.*)?>/g, "$1$3");

实现方案

方案1:正则快速实现(适合格式规范的固定场景XML)

核心逻辑是仅匹配标签起始位置(<或</后)的命名空间前缀,不会误改属性中的xmlns声明,代码简洁且完全匹配需求:

const result = xmlStr.replace(/<(\/?)[\w-]+:/g, '<$1');

正则说明:

  • 匹配<开头,后跟可选的闭合标签标记/
  • 匹配后续合法前缀名(支持字母、数字、下划线、横杠格式)和冒号
  • 替换时保留<和闭合标记/,仅删除前缀和冒号部分
  • 属性中的xmlns:xx内容不在标签名位置,不会被匹配修改

方案2:XML解析器实现(适合复杂生产场景,无正则边界问题)

如果XML包含CDATA、特殊字符、注释等复杂内容,正则可能出现误匹配,推荐用原生XML解析器处理:

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlStr, "text/xml");

// 递归移除所有元素的命名空间前缀
function removeNsPrefix(node) {
  if (node.nodeType === Node.ELEMENT_NODE) {
    const newNode = xmlDoc.renameNode(node, null, node.localName);
    node.parentNode?.replaceChild(newNode, node);
  }
  const childList = Array.from(node.childNodes);
  childList.forEach(child => removeNsPrefix(child));
}

removeNsPrefix(xmlDoc.documentElement);
const serializer = new XMLSerializer();
// 如果需要保留原始xmlns属性,可在序列化前手动将对应属性加回根节点
const result = serializer.serializeToString(xmlDoc.documentElement);

内容的提问来源于stack exchange,提问作者Luiz Alves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 00:21:49