当前位置 : 主页 > 网页制作 > xml >

解组转义XML

来源:互联网 收集:自由互联 发布时间:2021-06-13
在Go中,我将如何解码此 XML响应?我已经尝试在我的Answer结构上构建一个自定义的UnMarshal方法,但我没有太多运气. ?xml version="1.0"?GetAssignmentResponse Answerlt;?xml version="1.0" encoding="UTF-8" standa
在Go中,我将如何解码此 XML响应?我已经尝试在我的Answer结构上构建一个自定义的UnMarshal方法,但我没有太多运气.

<?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>
像这样解码它两次( try on playground)

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)
}
网友评论