Reputation: 194
Scenario: I have an XML structure I'm trying to parse, I don't know how to set up a struct where the value of an xml attribute contains text and more nested values. All other attributes have been set properly, I'm not sure if I'll need to get the value of the source and create a separate parser to retrieve the values of the elements.
<trans-unit id="some.message">
<source>hello %<ph id="first_name">{0}</ph> %<ph id="last_name">{1}</ph>
</source>
<target/>
</trans-unit>
type TransUnit struct {
Id string `xml:"id,attr"`
Source string `xml:"source"`
SourceVars MixedVars `xml:"source>ph"`
Target string `xml:"target"`
}
type MixedVars []MixedVar
type MixedVar struct {
VarName string `xml:"id,attr"`
}
EDIT: I'm trying to parse the source into a string that follows the form: hello %{first_name} %{last_name}
Unmarshalling the xml string with the current structs returns a an empty struct
@plato using innerxml sets the source to:
<source>Are you sure you want to reset the reservation for %<ph id="first_name">{0}</ph> %<ph id="last_name">{1}</ph>
This puts me in a similar situation where I still have nested xml tags interpolated within the source value
Upvotes: 3
Views: 2059
Reputation: 7071
It's possible to unmarshal the source xml node into both the raw xml and a slice of variables at once, eg:
type TransUnit struct {
ID string `xml:"id,attr"`
Source Source `xml:"source"`
Target string `xml:"target"`
}
type Source struct {
Raw string `xml:",innerxml"`
Text string `xml:",chardata"`
Vars []Var `xml:"ph"`
}
type Var struct {
ID string `xml:"id,attr"`
Value string `xml:",innerxml"`
}
See a running example. You should be good to go from there.
Upvotes: 4