Unmarshaling XML with some unknown tags in golang?

WBOY
Release: 2024-02-08 22:45:09
forward
1137 people have browsed it

在 golang 中使用一些未知标签解组 XML?

In golang, we often need to process XML data. However, sometimes we may encounter some unknown tags, which brings some difficulties to unmarshaling XML data. So, how to deal with these unknown tags in golang? In this article, PHP editor Xinyi will introduce some methods of handling unknown tags in golang to help you better unmarshal XML data. Whether you are a newbie or an experienced developer, this article can provide you with useful tips and guidance. let's start!

Question content

Given an XML raw string of unknown structure (from OCR result), how should I unmarshal the string into a processable go structure/interface?

With JSON I can do something like this, so is there an XML version of the answer?

Example

randomOcrXmlString := `
<container>
<x></x>
<y><z></z><y>
<abc></abc>
... (many more random tags)
</container>`
Copy after login

My actual intention - insert a tag before the closing </container> tag

Workaround

According to encoding/xml document,

So the following works for me

type xmlResponse struct {
    Fields []byte `xml:",innerxml"`
}

func isXMLStringValid(str string) bool {
    // ref https://stackoverflow.com/a/62869933
    decoder := xml.NewDecoder(strings.NewReader(str))
    for {
        err := decoder.Decode(new(interface{}))
        if err != nil {
            return err == io.EOF
        }
    }
}

func parseRawXMLString(xmlStr string) (*xmlResponse, error) {
  if !isXMLStringValid(xmlStr) {
        return nil, errors.New(fmt.Sprintf("xml: construct: input is not valid xml: %s", xmlStr))
    }

  var xmlResp = xmlResponse{}
  err := xml.Unmarshal([]byte(xmlStr), &xmlResp)
  if err != nil {
        log.Printf("xml: unmarshal: %s", err)
        return nil, err
  }
  return &xmlResp, nil
}
Copy after login

The above is the detailed content of Unmarshaling XML with some unknown tags in golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!