go - Custom xml decoder issue -
go - Custom xml decoder issue -
i have multiple test cases pass, 1 fails. missing here causing decoder read content of target keys incorrectly?
const respgenericfault1 = `<?xml version='1.0' encoding='utf-8'?> <soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/xmlschema-instance" xmlns:xsd="http://www.w3.org/1999/xmlschema"> <soap-env:body> <soap-env:fault> <faultcode xsi:type="xsd:string">soap-env:client</faultcode> <faultstring xsi:type="xsd:string">failed validate</faultstring> </soap-env:fault> </soap-env:body> </soap-env:envelope>` type fault struct { faultcode, faultstring string } func (f fault) error() string { homecoming "fault code: '" + f.faultcode + "' faultstring: '" + f.faultstring + "'" } func parsefault(b []byte) error { reader := bytes.newreader(b) d := xml.newdecoder(reader) var start xml.startelement fault := fault{} found := false // iterate through tokens { tok, _ := d.token() if tok == nil { break } // switch on token type switch t := tok.(type) { case xml.startelement: start = t.copy() fmt.println(start.name.local) case xml.chardata: key := strings.tolower(start.name.local) // fault found, capture values , mark found if key == "faultcode" { found = true fault.faultcode = string(t) fmt.printf("%#v\n", string(t)) } else if key == "faultstring" { found = true fault.faultstring = string(t) } } } if found { homecoming fault } homecoming nil } func main() { err := parsefault([]byte(respgenericfault1)) fmt.printf("%#v\n", err) }
here playground url: http://play.golang.org/p/7pfpnsmast
your code captures faultstring
, faultcode
, unintentionally overwrites xml.chardata
containing whitespace between tags.
here fixed version: http://play.golang.org/p/s1affytwcx . comment out line 52 see failure mode.
alternatively, can utilize encoding/xml unmarshal
parse xml straight struct. see http://play.golang.org/p/loszruj63b
go
Comments
Post a Comment