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

如何在Golang中修改XML并移除外层包装仅返回内容

使用etree库提取SOAP Body内的XML内容

完全可以用etree库实现这个需求,核心思路是定位到SOAP Body元素,提取其内部内容并重新生成符合要求的XML文档。具体步骤和代码示例如下:

实现步骤

  • 解析原始SOAP XML文档
  • 通过命名空间定位到soap:Body元素
  • 获取soap:Body下的子元素(这里是<contents>)
  • 创建新的XML文档,添加XML声明后将<contents>元素作为根节点
  • 格式化输出最终XML

示例代码

package main

import (
	"fmt"
	"github.com/beevik/etree"
)

func main() {
	// 原始SOAP XML内容
	soapXML := `<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.opentravel.org/OTA/2003/05">
    <soap:Header/>
    <soap:Body>
        <contents>
            <article>
                <category>Server</category>
                <title>Connect to Oracle Server using Golang and Go-OCI8 on Ubuntu</title>
                <url>/go-oci8-oracle-linux/</url>
            </article>
            <article>
                <category>Server</category>
                <title>Easy Setup OpenVPN Using Docker DockVPN</title>
                <url>/easy-setup-openvpn-docker/</url>
            </article>
            <article info="popular article">
                <category>Server</category>
                <title>Setup Ghost v0.11-LTS, Ubuntu, Nginx, Custom Domain, and SSL</title>
                <url>/ghost-v011-lts-ubuntu-nginx-custom-domain-ssl/</url>
            </article>
        </contents>
    </soap:Body>
</soap:Envelope>`

	// 解析XML文档
	doc := etree.NewDocument()
	if err := doc.ReadFromString(soapXML); err != nil {
		panic(err)
	}

	// 定义SOAP命名空间URI,用于定位元素
	soapNS := "http://schemas.xmlsoap.org/soap/envelope/"

	// 查找soap:Body元素
	bodyElem := doc.FindElement("//soap:Body", soapNS)
	if bodyElem == nil {
		panic("未找到soap:Body元素")
	}

	// 获取Body内的第一个子元素(即contents节点)
	contentsElem := bodyElem.FirstChild()
	if contentsElem == nil {
		panic("soap:Body内无有效内容")
	}

	// 创建新的XML文档
	newDoc := etree.NewDocument()
	// 添加XML声明
	newDoc.CreateProcInst("xml", `version="1.0" encoding="UTF-8"`)
	// 复制contents节点作为新文档的根节点
	newDoc.SetRoot(contentsElem.Copy())

	// 设置缩进格式,让输出更美观
	newDoc.Indent(2)
	// 转换为字符串输出
	output, err := newDoc.WriteToString()
	if err != nil {
		panic(err)
	}

	fmt.Println(output)
}

代码说明

  • 用FindElement时必须指定SOAP命名空间URI,因为原始XML中的soap是前缀,对应固定的命名空间地址
  • 使用Copy()方法复制节点,避免修改原始文档的结构
  • 通过CreateProcInst添加XML声明,确保输出符合要求的格式
  • Indent(2)用于设置输出的缩进空格数,让XML结构更清晰

内容的提问来源于stack exchange,提问作者David Async

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:35:24