如何在GO中解码灵活的XML?

3

我有以下xml:

    ...
    <solution>
      <ContainerBlockElement>
        <Paragraph>
           <Paragraph>
              Foo
           </Paragraph>
           <Paragraph>
              bar
           </Paragraph>
       </Paragraph>
     </ContainerBlockElement>
   </solution>
   ...

我想要提取内容,但问题是:服务器可以发送给我第二个结构:

    ...
    <solution>
      <ContainerBlockElement>
        <Paragraph>
          baz
        </Paragraph>
      </ContainerBlockElement>
    </solution>
    ...

我尝试在go中使用这个struct解码,但它没有起作用:

       type Blah struct {
           ...
    Solutions           []string     `xml:"solution>ContainerBlockElement>Paragraph"`
    Solutions2Paragraph []string         `xml:"solution>ContainerBlockElement>Paragraph>Paragraph"`

}

我该如何解码这个字符串?
1个回答

4

由于结构不可预测,将其反序列化为结构体是行不通的。相反,您最好使用XML解析器的流模式,使用xml.Decoder.Token按顺序解析元素,并根据需要处理它们。

decoder := xml.NewDecoder(xmlFile) 
solutions := make([]string,0,0)

for { 
    t, _ := decoder.Token() 
    if t == nil { 
        break 
    }
    switch se := t.(type) { 
    case xml.StartElement: 
        if se.Name.Local == "Paragraph" {
            // Get the next token after the Paragraph start element, which will be the tag contents
            innerText,ok := decoder.Token().(xml.CharData)
            if !ok {
                continue
            }
            solutions = append(solutions, string(innerText))
        }
    }
}

这段代码未经测试,但应该提供一个不错的起点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接