小编典典

解组转义的XML

go

在Go中,我将如何解码该XML响应?我尝试UnMarshal在自己的Answer结构上构建自定义方法,但是运气不高。

<?xml version="1.0"?>
<GetAssignmentResponse>
    <Answer>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;
        &lt;QuestionFormAnswers xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionFormAnswers.xsd"&gt;
        &lt;Answer&gt;
        &lt;QuestionIdentifier&gt;Q1HasEvents&lt;/QuestionIdentifier&gt;
        &lt;FreeText&gt;no&lt;/FreeText&gt;
        &lt;/Answer&gt;
        &lt;/QuestionFormAnswers&gt;
    </Answer>
</GetAssignmentResponse>

阅读 243

收藏
2020-07-02

共1个答案

小编典典

像这样两次解码(在操场上尝试

package main

import (
    "encoding/xml"
    "fmt"
)

var data = `<?xml version="1.0"?>
<GetAssignmentResponse>
    <Answer>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;
        &lt;QuestionFormAnswers xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionFormAnswers.xsd"&gt;
        &lt;Answer&gt;
        &lt;QuestionIdentifier&gt;Q1HasEvents&lt;/QuestionIdentifier&gt;
        &lt;FreeText&gt;no&lt;/FreeText&gt;
        &lt;/Answer&gt;
        &lt;/QuestionFormAnswers&gt;
    </Answer>
</GetAssignmentResponse>`

type Response struct {
    XMLName xml.Name `xml:"GetAssignmentResponse"`
    Answer  string   `xml:"Answer"`
}

type Answer struct {
    XMLName  xml.Name `xml:"QuestionFormAnswers"`
    FreeText string   `xml:"FreeText"`
}

func main() {
    v := Response{}
    err := xml.Unmarshal([]byte(data), &v)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("Answer = %q\n", v.Answer)
    a := Answer{}
    err = xml.Unmarshal([]byte(v.Answer), &a)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("Answer = %#v\n", a)
}
2020-07-02