利用多重前缀名称定义 XML 信封的结构
时间:2024-02-22
浏览:378
作者:佚名
哈喽!今天心血来潮给大家带来了《利用多重前缀名称定义 XML 信封的结构》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
如何向 xml.name 类型添加多个值?
// envelope type
type envelope struct {
xmlname xml.name `xml:"http://schemas.xmlsoap.org/soap/envelope/ soap-env:envelope"`
header header
body body
}
xml 信封的预期结果
<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:login" xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance">
第一个代码的当前输出如下:
<SOAP-ENV:Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
解决方案
当编组 xml 在标准库中显示为 work in progress 时,支持名称空间前缀。
使用 xml.Marshal 获得所需输出的一种方法是在 envelope 结构中使用 ...,attr 标记声明 string 字段:
带有标签“name,attr”的字段成为带有 xml 元素中的给定名称。
// envelope type
type envelope struct {
xmlname xml.name `xml:"soap-env:envelope"`
xmlnssoapenv string `xml:"xmlns:soap-env,attr"`
xmlnsurn string `xml:"xmlns:urn,attr"`
xmlnsxsd string `xml:"xmlns:xsd,attr"`
xmlnsxsi string `xml:"xmlns:xsi,attr"`
header header
body body
}
然后,在初始化 envelope 结构时,将所需的字符串值分配给这些字段:
func main() {
e := &envelope{
xmlnssoapenv: "http://schemas.xmlsoap.org/soap/envelope/",
xmlnsurn: "urn:login",
xmlnsxsd: "http://www.w3.org/2001/xmlschema",
xmlnsxsi: "http://www.w3.org/2001/xmlschema-instance",
}
a, err := xml.marshalindent(e, "", "\t")
if err != nil {
panic(err)
}
fmt.println(string(a))
}
这个outputs:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:login" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Header></Header>
<Body></Body>
</SOAP-ENV:Envelope>本篇关于《利用多重前缀名称定义 XML 信封的结构》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
