golang xml 处理动态属性

golang处理读写xml时,是和一个结构体对应的。

因此,每个每个xml节点的属性,都是结构体的字段,是定死的。

type Student struct{
	Name string
	Address Addr
}
type Addr struct {
	City string `xml:"city"`
	Build string  `xml:"build,attr"`
}

<Student>
  <Name>gaofeng</Name>
  <Address build="2b">
    <city>sz</city>
  </Address>
</Student>

但是如果有些属性是动态,比如

待解析/待生成的数据可能是数据1,也可能是数据2. 就是说MyItem有哪些属性,不是提前定死的。

数据1:
<Student>
  <Name>gaofeng</Name>
  <Address build="2b">
     <city>sz</city>
       <MyItem 临时1="vvv&amp;11" 临时2="vvv22">
     </MyItem>
  </Address>
</Student>

数据2:
<Student>
  <Name>gaofeng</Name>
  <Address build="2b">
     <city>sz</city>
       <MyItem  临时4="vvv22">
     </MyItem>
  </Address>
</Student>

可以使用下面的代码进行处理

package main

import (
	"encoding/xml"
	"fmt"
)
type Student struct{
	Name string
	Address Addr
}
type Addr struct {
	City string `xml:"city"`
	Build string  `xml:"build,attr"`
	MyItem Item
}

type Item struct {
	Attributes []xml.Attr `xml:",any,attr"`
}

func main() {

	p := &Student{Name:"gaofeng", Address:Addr{City:"sz",Build:"2b"}}

	p.Address.MyItem = Item{}
	p.Address.MyItem.Attributes = []xml.Attr{}
	tt:=xml.Attr{Name: xml.Name{ Space:"", Local :"临时1" }, Value:"vvv&11"}
	p.Address.MyItem.Attributes = append(p.Address.MyItem.Attributes, tt)

	tt=xml.Attr{Name: xml.Name{ Space:"", Local :"临时2" }, Value:"vvv22"}
	p.Address.MyItem.Attributes = append(p.Address.MyItem.Attributes, tt)
    
    // 生成xml
	buf, _ := xml.Marshal(p)
	fmt.Println(string(buf))

     // 解析xml
	var s = `<Student><Name>gaofeng</Name><Address build="2b"><city>sz</city><MyItem 临时1="vvv&amp;11" 临时2="vvv22"></MyItem></Address></Student>`
	fmt.Println(s)
	pp := new(Student)
	xml.Unmarshal([]byte(s), pp)
	fmt.Println(pp.Address.City)
	fmt.Println(pp.Address.MyItem.Attributes[0].Value)
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值