结构定义 XML 具有多个前缀命名空间的信封

Struct defining XML Envelope with multiple prefixed namespaces

如何向 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 字段:

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>