自定义xml解码器问题

时间:2014-10-06 15:34:15

标签: go

我有多个测试用例通过,但是这个测试用例失败了。我在这里错过了什么导致解码器错误地读取目标键的内容?

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 to validate</faultstring>
     </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>`

type Fault struct {
    FaultCode, FaultString string
}

func (f Fault) Error() string {
    return "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 the tokens
    for {
        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 was found, capture the values and mark as 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 {
        return fault
    }
    return nil
}

func main() {
    err := ParseFault([]byte(respGenericFault1))
    fmt.Printf("%#v\n", err)
}

这是游乐场网址:http://play.golang.org/p/7PFPNsmast

1 个答案:

答案 0 :(得分:2)

您的代码成功捕获了faultstringfaultcode,但随后无意中用xml.CharData覆盖了包含标记之间空格的内容。

以下是固定版本:http://play.golang.org/p/s1aFFYtwcX。注释掉第52行以查看失败模式。

或者,您可以使用encoding/xml Unmarshal将XML直接解析为结构。见http://play.golang.org/p/lOsZRUJ63B