登录
首页 >  Golang >  Go问答

如何使用 goland 制作嵌套 xml by go xml marshal

来源:stackoverflow

时间:2024-03-17 10:06:29 198浏览 收藏

在使用 Go 语言处理 XML 时,嵌套 XML 结构的创建可以通过 xml.marshalindent 函数实现。通过定义嵌套的 XML 结构体,并使用 xml 标记进行属性和元素的定义,可以生成所需的 XML 文档。在具体实现中,需要为嵌套的结构体定义属性和元素,并设置其命名空间和值,以匹配目标 XML 的结构。通过设置 xmlns 属性,可以指定命名空间,而通过使用 xml 标记,可以定义元素和属性的名称和类型。最终,通过调用 xml.marshalindent 函数,可以将结构体转换为缩进格式的 XML 文档。

问题内容

我有一个肥皂请求,我需要制作一个 xml 来发出请求。 所以我所做的制作 xml 如下所示:

type command struct {
        xmlname xml.name
    }

    type xmlenvelop struct {
        xmlname        xml.name `xml:"soapenv:envelope"`
        xmlns          string   `xml:"xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/,"`
        calculateprice command  `xml:"soapenv:body>functionname"`
    }

    v := &xmlenvelop{xmlns: "namespace1", calculateprice: command{xml.name{"namespace2", "calculateprice"}}}

    output, err := xml.marshalindent(v, "", "    ")
    if err != nil {
        fmt.printf("error: %v\n", err)
    }

    // write the output to check
    os.stdout.write(output)

这会给我这个输出:


    namespace1
    
        
    

现在我想在 calculateprice 中创建一些字段,我在网上找不到它,所以 xml 的例子如下:


        somevalue
        somevalue
        

正确答案


请更改 struct command 和 xmlenvelop :-

type command struct {
    xmlns string `xml:"xmlns,attr"`
    test string `xml:"test"`
    someothertest string `xml:"someothertest"`  
}
type XMLEnvelop struct {
    XMLName        xml.Name `xml:"soapenv:Envelope"`
    Xmlns          string   `xml:"xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/,"`
    CalculatePrice Command  `xml:"soapenv:Body>CalculatePrice"`
}

并更改 v := &xmlenvelop{xmlns: "namespace1",calculateprice: command{xmlns: "namespace2",test: "somevalue", someothertest: "somevalue"}}

Test In Playground

终于介绍完啦!小伙伴们,这篇关于《如何使用 goland 制作嵌套 xml by go xml marshal》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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