如何为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时,对 namespace 前缀的支持似乎是work in progress。
使用 xml.Marshal
获得所需输出的一种方法是在string
结构中使用...,attr
标记声明Envelope
字段:
a field with tag "name,attr" becomes an attribute with the given name in the XML element.
// 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 - 用多个带前缀的 namespace 构造XML信封,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62970734/