-
Notifications
You must be signed in to change notification settings - Fork 113
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This was inspired by https://www.reddit.com/r/golang/comments/9eclgy/xml_unmarshaling_internal_references/
- Loading branch information
Showing
3 changed files
with
127 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
// https://www.reddit.com/r/golang/comments/9eclgy/xml_unmarshaling_internal_references/ | ||
|
||
package main | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/clbanning/mxj" | ||
) | ||
|
||
var data = []byte(`<app> | ||
<users> | ||
<user id="1" name="Jeff" /> | ||
<user id="2" name="Sally" /> | ||
</users> | ||
<messages> | ||
<message id="1" from_user="1" to_user="2">Hello!!</message> | ||
</messages> | ||
</app>`) | ||
|
||
func main() { | ||
m, err := mxj.NewMapXml(data) | ||
if err != nil { | ||
fmt.Println("err:", err) | ||
return | ||
} | ||
fmt.Printf("%v\n", m) | ||
|
||
type mystruct struct { | ||
FromUser string | ||
ToUser string | ||
Message string | ||
} | ||
myStruct := mystruct{} | ||
val, err := m.ValueForKey("user", "-id:1") | ||
if val != nil { | ||
myStruct.FromUser = val.(map[string]interface{})["-name"].(string) | ||
} else { | ||
// if there no val, then err is at least KeyNotExistError | ||
fmt.Println("err:", err) | ||
return | ||
} | ||
val, err = m.ValueForKey("user", "-id:2") | ||
if val != nil { | ||
myStruct.ToUser = val.(map[string]interface{})["-name"].(string) | ||
} else { | ||
// if there no val, then err is at least KeyNotExistError | ||
fmt.Println("err:", err) | ||
return | ||
} | ||
val, err = m.ValueForKey("#text") | ||
if val != nil { | ||
myStruct.Message = val.(string) | ||
} else { | ||
// if there no val, then err is at least KeyNotExistError | ||
fmt.Println("err:", err) | ||
return | ||
} | ||
|
||
fmt.Printf("%#v\n", myStruct) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters