Danish
Danish

Reputation: 3798

Parsing Unexpected Fields in XML to a Struct using Go

Lets say we have an XML document that looks like this, which has an unexpected tag <custom1> on <item>

<item>
  <name>...</name>
  <price>...</price>
  <custom1>...</custom1>
</item>

The struct to parse this looks like this

type Item struct {
    Name     string   `xml:"name"`
    Price    string   `xml:"price"`
}

I don't have Custom1 in there since I'm not expecting it. However, is it possible to capture the remaining tags OR the raw representation of the <item> inside the Item struct?

Upvotes: 0

Views: 159

Answers (1)

Ainar-G
Ainar-G

Reputation: 36199

Use a field with ,innerxml tag:

type Item struct {
    Name  string `xml:"name"`
    Price string `xml:"price"`
    Other string `xml:",innerxml"`
}

Playground: https://play.golang.org/p/Io2CDjSiwx.

Upvotes: 2

Related Questions