登录
首页 >  Golang >  Go问答

golang中如何修改xml并仅返回非包装器内容

来源:stackoverflow

时间:2024-02-07 17:00:23 478浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《golang中如何修改xml并仅返回非包装器内容》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我有一个像这样的 xml 文件


    
    
        
            
server connect to oracle server using golang and go-oci8 on ubuntu /go-oci8-oracle-linux/
server easy setup openvpn using docker dockvpn /easy-setup-openvpn-docker/
server setup ghost v0.11-lts, ubuntu, nginx, custom domain, and ssl /ghost-v011-lts-ubuntu-nginx-custom-domain-ssl/

我想修改它只返回这样


 
    
Server Connect to Oracle Server using Golang and Go-OCI8 on Ubuntu /go-oci8-oracle-linux/
Server Easy Setup OpenVPN Using Docker DockVPN /easy-setup-openvpn-docker/
Server Setup Ghost v0.11-LTS, Ubuntu, Nginx, Custom Domain, and SSL /ghost-v011-lts-ubuntu-nginx-custom-domain-ssl/

所以我想删除包装并只选择 soap:body 也许有一些使用 etree 的解决方案(https://pkg.go.dev/github.com/beevik/etree#element)?

================================================== ===========


正确答案


标准库足以胜任这项任务。只需解析 xml 文档,使用 xml:",innerxml" 作为 body 元素即可使用内部的任意 xml。然后你就可以把它吐出来了。

package main

import (
    "bytes"
    "encoding/xml"
    "io"
    "log"
    "os"
)

var src = []byte(`

    
    
        
            
Server Connect to Oracle Server using Golang and Go-OCI8 on Ubuntu /go-oci8-oracle-linux/
`) type envelope struct { XMLName xml.Name `xml:"Envelope"` Body struct { InnerXML []byte `xml:",innerxml"` } } func main() { var e envelope if err := xml.Unmarshal(src, &e); err != nil { log.Fatal(err) } io.WriteString(os.Stdout, xml.Header) os.Stdout.Write(bytes.TrimSpace(e.Body.InnerXML)) }

在演示中尝试一下:https://go.dev/play/p/CUEpuPfh_Xl

本篇关于《golang中如何修改xml并仅返回非包装器内容》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>