Home > OS >  Golang XML: how to get xml attribute in header in string map
Golang XML: how to get xml attribute in header in string map

Time:10-03

Suppose, I have an XML like this

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.opentravel.org/OTA/2003/05">
    <soap:Header/>
    <soap:Body>
        <contents>
            <article>
                <category>Server</category>
                <title>Connect to Oracle Server using Golang and Go-OCI8 on Ubuntu</title>
                <url>/go-oci8-oracle-linux/</url>
            </article>
            <article>
                <category>Server</category>
                <title>Easy Setup OpenVPN Using Docker DockVPN</title>
                <url>/easy-setup-openvpn-docker/</url>
            </article>
            <article info="popular article">
                <category>Server</category>
                <title>Setup Ghost v0.11-LTS, Ubuntu, Nginx, Custom Domain, and SSL</title>
                <url>/ghost-v011-lts-ubuntu-nginx-custom-domain-ssl/</url>
            </article>
        </contents>
    </soap:Body>
</soap:Envelope>

How to get a map that return the attribute at the root element (the key value is dynamic, not always xmlns:soap and xmlns:ns)

{ "xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:ns": "http://www.opentravel.org/OTA/2003/05" }

and also how to get this string soap:Envelope?

assuming structure is not always soap:Envelope, so it can be soap:Foo

CodePudding user response:

This seems to do it:

package main
import "encoding/xml"

var input = []byte(`
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:ns="http://www.opentravel.org/OTA/2003/05">
</soap:Envelope>
`)

func main() {
   var soap struct {
      Attrs   []xml.Attr `xml:",any,attr"`
      XMLName xml.Name
   } 
   err := xml.Unmarshal(input, &soap)
   if err != nil {
      panic(err)
   }
   println(soap.Attrs[1].Name.Local == "ns")
   println(soap.Attrs[1].Value == "http://www.opentravel.org/OTA/2003/05")
   println(soap.XMLName.Local == "Envelope")
}
  • Related