I need to parse xml code,
<claims>
<claim>
<claim-text>ABC
<claim-text>PQR</claim-text>
<claim-text>Xyz
<claim-text>A</claim-text>
<claim-text>B</claim-text>
<claim-text>C</claim-text>
</claim-text>
</claim-text>
</claim>
<claim>
<claim-text>PPP
<claim-text>ZZZ</claim-text>
<claim-text>MMM</claim-text>
</claim-text>
</claim>
How to get array of 'claim' with inside all claim texts? I was trying this but it does not give whatever text enclosed in claim-text.
type Result struct {
Claims []Claim `xml:"claims>claim"`
}
type Claim struct{
ClaimText []string `xml:"claim-text"`
}
Any help would be appreciated.
CodePudding user response:
type Result struct {
Claims []Claim `xml:"claim"`
}
type Claim struct {
ClaimText []ClaimText `xml:"claim-text"`
}
type ClaimText struct {
Value string `xml:",chardata"`
ClaimText []ClaimText `xml:"claim-text"`
}
https://play.golang.org/p/uueAiwG84LH
If you want to get rid of the white-space, you can implement the unmarshaler interface:
func (t *ClaimText) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
type T ClaimText
if err := d.DecodeElement((*T)(t), &start); err != nil {
return err
}
t.Value = strings.TrimSpace(t.Value)
return nil
}
https://play.golang.org/p/2I1meeBm0pu
CodePudding user response:
Take a look at this online tool that generate the following struct:
type Claims struct {
XMLName xml.Name `xml:"claims"`
Text string `xml:",chardata"`
Claim []struct {
Text string `xml:",chardata"`
ClaimText struct {
Text string `xml:",chardata"`
ClaimText []struct {
Text string `xml:",chardata"`
ClaimText []string `xml:"claim-text"`
} `xml:"claim-text"`
} `xml:"claim-text"`
} `xml:"claim"`
}