D
D
Darlov2016-02-17 13:56:49
go
Darlov, 2016-02-17 13:56:49

Golang Parsing XML, how to create an arbitrary type?

Hello, please tell me, I'm trying to parse XML, I use "encoding / xml", everything is OK,
I want to make it more dynamic, so that the user indicates the location of the branch
There is such a structure

type XMLShop struct {
  XMLName xml.Name `xml:"shop"`
  Name string `xml:"name"`
  Company string `xml:"company"`
  Url string `xml:"url"`
  Categories []*XMLShopCategories `xml:"categories>category"`
}

How can I programmatically change these values ​​`xml:"shop"` `xml:"name"`
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2016-02-17
@ldar

You can do it like this https://play.golang.org/p/TANUVIEQA2

package main

import (
  "encoding/xml"
  "fmt"
)

type XMLShop struct {
  XMLName xml.Name    `xml:"shop"`
  Name    []NameField `xml:",any"`
  Company string      `xml:"company"`
  Url     string      `xml:"url"`
}

type NameField struct {
  XMLName xml.Name `xml:""`
  Value   string   `xml:",chardata"`
}

const data = `
<shop>
    <someOtherName>testname1</someOtherName>
    <custom_name>testname2</custom_name>
    <company>testcorp</company>
    <url>http://ya.ru</url>
</shop>
`

func main() {
  var shop XMLShop
  if err := xml.Unmarshal([]byte(data), &shop); err != nil {
    fmt.Println(err)
    return
  }
  for _, node := range shop.Name {
    if node.XMLName.Local == "custom_name" {
      fmt.Printf("Name: %+v\n", node.Value)
    }
  }
}

V
Vitaly Filinkov, 2016-02-17
@vitfil

You need dictionary support. Do not change anything in the structure itself. In the file received from the user, change the custom field names to the "correct" ones, making a substitution from the dictionary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question