dqypcghd381390 2014-10-06 15:34
浏览 37
已采纳

自定义xml解码器问题

I have multiple test cases which pass, however this one fails. What am I missing here that is causing the decoder read the content of my 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 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
", 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
", err)
}

Here is the playground url: http://play.golang.org/p/7PFPNsmast

  • 写回答

1条回答 默认 最新

  • dongyi3616 2014-10-06 16:02
    关注

    Your code successfully captures the faultstring and faultcode, but then unintentionally overwrites it with xml.CharData containing the whitespace between tags.

    Here is a fixed version: http://play.golang.org/p/s1aFFYtwcX . Comment out line 52 to see the failure mode.

    Alternatively, you can use encoding/xml Unmarshal to parse the XML directly into a struct. See http://play.golang.org/p/lOsZRUJ63B

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计