xml - 如何在 GO 中解码灵活的 xml?

标签 xml go xml-parsing

我有以下 xml:

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

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

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

我尝试在 go 解码中使用这个结构,但它不起作用:

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

}

我该如何解码?

最佳答案

对于不可预测的结构,反序列化为结构是行不通的。相反,您最好使用 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))
        }
    }
}

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

关于xml - 如何在 GO 中解码灵活的 xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45803618/

相关文章:

xml - 通过 XML 中的多个属性查找

java - 是否有一种可以在格式之间动态转换的模式?

java - 如何列出 xml 文件中的特定属性

concurrency - Golang channel 选择语句

go - 在 Go 文本模板中遍历 map

java - XMLGregorianCalendar 日期比较

compiler-construction - 如何在windows下编译golang源码

java - android应用程序中的xml解析文件存储在哪里

JSF 在 SVG 之后吞下结束标记

python - 在 Python 的 ElementTree 中提取标签后的文本