go - How do I retain the outer XML of sub-elements? -


i have xml file contains list of individual <order/> elements. split single xml file multiple files, each of contain single order.

example input file:

<orders>   <order order-id="123">     <line-item product-id="abc">abc</line-item>   </order>   <order order-id="456">     <line-item product-id="def">def</line-item>   </order> </orders> 

desired outputs:

order-123.xml:

 <order order-id="123">    <line-item product-id="abc">abc</line-item>  </order> 

order-456.xml:

 <order order-id="456">    <line-item product-id="def">def</line-item>  </order> 

at stage, not concerned unmarshalling each of order details struct; merely want exact copy of each <order/> node in own file.

i have tried few variations of using xml:",innerxml", like this:

type ordersraw struct {   orders []orderraw `xml:"order"` }  type orderraw struct {   order string `xml:",innerxml"` } 

the problem in above code each order value contains inner xml (starting <line-item/>) not contain wrapping <order/> tag.

ideally, if there xml:",outerxml" tag, serve purpose.

i trying avoid doing hacky things manually concatenating inner xml handwritten xml (e.g. <order order-id="123">).

use xmlname on orderraw:

type orderraw struct {     xmlname xml.name `xml:"order"`     order   string   `xml:",innerxml"`     orderid string   `xml:"order-id,attr"` } 

playground: https://play.golang.org/p/onk5fexqzd.


edit: if want save all attributes, you'll have use marshalerxml , unmarshalerxml interfaces:

func (o *orderraw) unmarshalxml(d *xml.decoder, start xml.startelement) error {     o.attrs = map[xml.name]string{}     _, := range start.attr {         o.attrs[a.name] = a.value     }     type order orderraw     return d.decodeelement((*order)(o), &start) }  func (o orderraw) marshalxml(e *xml.encoder, start xml.startelement) error {     name, attr := range o.attrs {         start.attr = append(start.attr, xml.attr{name: name, value: attr})     }     start.name = xml.name{local: "order"}     type order orderraw     return e.encodeelement(order(o), start) } 

playground: https://play.golang.org/p/xhkwqjfymd.


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -