当前位置: > > > > Golang XML:如何获取字符串映射中标头中的 xml 属性
Golang XML:如何获取字符串映射中标头中的 xml 属性
来源:stackoverflow
2024-04-24 19:48:35
0浏览
收藏
编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天米云就整理分享《Golang XML:如何获取字符串映射中标头中的 xml 属性》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过米云,在这可以对大家的知识积累有所帮助,助力开发能力的提升。
问题内容
假设,我有一个像这样的 xml
<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>
如何获取返回根元素处属性的映射(键值是动态的,并不总是 xmlns:soap 和 xmlns:ns)
{ "xmlns:soap": "http://schemas.xmlsoap.org/soap/envelope/", "xmlns:ns": "http://www.opentravel.org/ota/2003/05 “ }
以及如何获取此字符串 soap:envelope?
假设结构并不总是 soap:envelope,因此它可以是 soap:foo
正确答案
这似乎可以做到:
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")
}
好了,本文到此结束,带大家了解了《Golang XML:如何获取字符串映射中标头中的 xml 属性》,希望本文对你有所帮助!关注米云公众号,给大家分享更多Golang知识!
