func TestNamespaceLookup(t *testing.T) { type Media struct { Title string `xml:"media title"` } type Item struct { Id string `xml:"id"` Media } var data string = ` <item xmlns:media="X2"> <media:title>sup</media:title> <id>123</id> </item> ` var items Item err := xml.Unmarshal([]byte(data), &items) if err != nil { t.Error(err) } if items.Media.Title == "" { t.Error("Title should not be empty..") } t.Log(items.Media.Title) }
// This example demonstrates unmarshaling an XML excerpt into a value with // some preset fields. Note that the Phone field isn't modified and that // the XML <Company> element is ignored. Also, the Groups field is assigned // considering the element path provided in its tag. func ExampleUnmarshal() { 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:"FullName"` Phone string Email []Email Groups []string `xml:"Group>Value"` Address } v := Result{Name: "none", Phone: "none"} data := ` <Person> <FullName>Grace R. Emlin</FullName> <Company>Example Inc.</Company> <Email where="home"> <Addr>[email protected]</Addr> </Email> <Email where='work'> <Addr>[email protected]</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) // Output: // XMLName: xml.Name{Space:"", Local:"Person"} // Name: "Grace R. Emlin" // Phone: "none" // Email: [{home [email protected]} {work [email protected]}] // Groups: [Friends Squash] // Address: {Hanga Roa Easter Island} }