3 回答

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
cap是命名空間標(biāo)識(shí)符,而不是標(biāo)記名稱的一部分。這里是簡(jiǎn)寫(xiě)urn:oasis:names:tc:emergency:cap:1.1
(這個(gè)答案看起來(lái)可能對(duì)命名空間有一個(gè)很好的濃縮解釋:XML 中的“xmlns”是什么意思?)
Go“encoding/xml”包不能很好地處理命名空間,但如果沒(méi)有沖突的標(biāo)簽,你可以完全省略命名空間
type Entry struct {
Summary string `xml:"summary"`
Event string `xml:"event"`
}
指定事件的正確方法,尤其是在不同命名空間中具有相同標(biāo)簽的情況下,將使用完整命名空間,例如:
type Entry struct {
Summary string `xml:"summary"`
Event string `xml:"urn:oasis:names:tc:emergency:cap:1.1 event"`
}
這是一個(gè)工作示例:https : //play.golang.org/p/ry55F2pWKY

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
cap不是標(biāo)記名稱的一部分,而是命名空間標(biāo)識(shí)符(urn:oasis:names:tc:emergency:cap:1.1如您在評(píng)論中提供的那樣的縮寫(xiě))。這是正確的符號(hào):
type Entry struct{
Summary string `xml:"summary"`
Cevent string `xml:"urn:oasis:names:tc:emergency:cap:1.1:cap event"`
}
注意空格而不是:表示命名空間。另請(qǐng)注意,僅使用名稱空間標(biāo)識(shí)符(如xml:"cap event")是行不通的。
工作示例(https://play.golang.org/p/rjkb2esGgv):
package main
import "fmt"
import "encoding/xml"
type Entry struct{
Summary string `xml:"summary"`
Cevent string `xml:"urn:oasis:names:tc:emergency:cap:1.1:cap event"`
}
func main() {
xmlString := []byte(`
<doc xmlns:cap = 'urn:oasis:names:tc:emergency:cap:1.1'>
<summary>...AIR QUALITY ALERT </summary>
<cap:event>Air Quality Alert</cap:event>
</doc>
`)
entry := new(Entry)
if err := xml.Unmarshal(xmlString, entry); err == nil {
fmt.Println(entry)
}
}

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
你只需要逃避冒號(hào)。因此,將您的 xml 標(biāo)記更改為xml:"cap\:event",它將按您的預(yù)期工作。
type Entry struct{
Summary string `xml:"summary"`
Cevent string `xml:"cap\:event"`
}
使用 unmarshal 示例在 xml 頁(yè)面上對(duì)此進(jìn)行了測(cè)試,并稍作修改;
package main
import (
"encoding/xml"
"fmt"
)
func main() {
type Email struct {
Where string `xml:"where,attr"`
Addr string
}
type Address struct {
City, State string
}
type Result struct {
XMLName xml.Name `xml:"Person"`
Name string `xml:"Full\:Name"`
Phone string
Email []Email
Groups []string `xml:"Group>Value"`
Address
}
v := Result{Name: "none", Phone: "none"}
data := `
<Person>
<Full:Name>Grace R. Emlin</Full:Name>
<Company>Example Inc.</Company>
<Email where="home">
<Addr>gre@example.com</Addr>
</Email>
<Email where='work'>
<Addr>gre@work.com</Addr>
</Email>
<Group>
<Value>Friends</Value>
<Value>Squash</Value>
</Group>
<City>Hanga Roa</City>
<State>Easter Island</State>
</Person>
`
err := xml.Unmarshal([]byte(data), &v)
if err != nil {
fmt.Printf("error: %v", err)
return
}
fmt.Printf("XMLName: %#v\n", v.XMLName)
fmt.Printf("Name: %q\n", v.Name)
fmt.Printf("Phone: %q\n", v.Phone)
fmt.Printf("Email: %v\n", v.Email)
fmt.Printf("Groups: %v\n", v.Groups)
fmt.Printf("Address: %v\n", v.Address)
}
刪除轉(zhuǎn)義符,它將為 Name 打印“none”。使用空格代替:or \:,它也可以工作。xml 中的空格會(huì)導(dǎo)致解析錯(cuò)誤,因?yàn)樗@然是無(wú)效的。
- 3 回答
- 0 關(guān)注
- 227 瀏覽
添加回答
舉報(bào)