在Go中,我将如何解码此XML响应?我已经尝试在我的UnMarshal
结构上构建自定义Answer
方法,但我没有太多运气。
<?xml version="1.0"?>
<GetAssignmentResponse>
<Answer><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<QuestionFormAnswers xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionFormAnswers.xsd">
<Answer>
<QuestionIdentifier>Q1HasEvents</QuestionIdentifier>
<FreeText>no</FreeText>
</Answer>
</QuestionFormAnswers>
</Answer>
</GetAssignmentResponse>
答案 0 :(得分:6)
将其解码两次(try on playground)
package main
import (
"encoding/xml"
"fmt"
)
var data = `<?xml version="1.0"?>
<GetAssignmentResponse>
<Answer><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<QuestionFormAnswers xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionFormAnswers.xsd">
<Answer>
<QuestionIdentifier>Q1HasEvents</QuestionIdentifier>
<FreeText>no</FreeText>
</Answer>
</QuestionFormAnswers>
</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)
}
答案 1 :(得分:1)
作为替代方案,这也有效,但它并不那么优雅
func (l *AssignmentAnswer) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var (
content string
resp QuestionFormAnswers
)
if err := d.DecodeElement(&content, &start); err != nil {
return err
}
c := strings.NewReader(html.UnescapeString(content))
dec := xml.NewDecoder(c)
if err := dec.Decode(&resp); err != nil{
return err
}
*l = AssignmentAnswer{resp}
return nil
}
type QuestionFormAnswers struct{
Answers []Answer `xml:"Answer"`
}
type AssignmentAnswer struct{
QuestionFormAnswers QuestionFormAnswers
}
type Assignment struct{
AssignmentId string
WorkerId string
HITId string
AssignmentStatus string
AutoApprovalTime string
AcceptTime string
SubmitTime string
ApprovalTime string
Answers AssignmentAnswer `xml:"Answer"`
}