为了账号安全,请及时绑定邮箱和手机立即绑定

Go XML 编码的问题

Go XML 编码的问题

Go
慕标琳琳 2023-05-22 17:12:11
我需要生成以下 xml:<AccessControlList>    <Grant>        <Grantee            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">            <ID>xxxx-xx</ID>            <DisplayName>rahul.khan</DisplayName>        </Grantee>        <Permission>FULL_CONTROL</Permission>    </Grant></AccessControlList>我的结构定义如下:type Grantee struct {Xmlns_xsi   string `xml:"xmlns xsi,attr,omitempty"`Xsi_type    string `xml:"http://www.w3.org/2001/XMLSchema-instance type,attr,omitempty"`ID          string `xml:",omitempty"`DisplayName string `xml:",omitempty"`}但是,当我整理此结构时,生成的结果 xml 文档如下所示:<AccessControlList>    <Grant>        <Grantee            xmlns:XMLSchema-instance="http://www.w3.org/2001/XMLSchema-instance" XMLSchema-instance:type="CanonicalUser">            <ID>xxxx-xx</ID>            <DisplayName>rahul.khan</DisplayName>        </Grantee>        <Permission>FULL_CONTROL</Permission>    </Grant></AccessControlList>结果,当文档被解组时,类型字段似乎没有被 aws-go-sdk 解析。例如,这是我需要得到的未编组输出Grantee: {    DisplayName: "rahul.khan",    ID: "xxxx-xx",    Type: "CanonicalUser"  },  Permission: "FULL_CONTROL"}相反,我得到的是:  Grantee: {    DisplayName: "rahul.khan",    ID: "xxxx-xx"  },  Permission: "FULL_CONTROL"}未编组的输出中似乎缺少 Type 属性。我在我的代码和 aws 生成的 xml 文档中看到的唯一区别是这一行xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser"比/秒xmlns:XMLSchema-instance="http://www.w3.org/2001/XMLSchema-instance" XMLSchema-instance:type="CanonicalUser"感谢是否有人可以帮助我了解如何解决此问题?
查看完整描述

1 回答

?
慕运维8079593

TA贡献1876条经验 获得超5个赞

这个结构 Marshals 到你需要的 XML,只使用 endcoding/xml.Marshal():


type Grantee struct {

    Xmlns_xsi   string `xml:"xmlns:xsi,attr,omitempty"`  //set namespace prefix explicitly

    Xsi_type    string `xml:"xsi:type,attr,omitempty"`   //set namespace:attr  explicitly

    ID          string `xml:",omitempty"`

    DisplayName string `xml:",omitempty"`

}


g := Grantee{

    DisplayName: "rahul.khan",

    ID:          "xxxx-xx",

    Xsi_type:    "CanonicalUser",

    Xmlns_xsi:   "http://www.w3.org/2001/XMLSchema-instance", // set namespace URI as the value of the field

}


gm, err := xml.MarshalIndent(g, "", "  ")

if err != nil {

    fmt.Printf("error: %v", err)

    return

}


fmt.Printf("%+s\n", gm)


//<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">

//  <ID>xxxx-xx</ID>

//  <DisplayName>rahul.khan</DisplayName>

//</Grantee>

https://play.golang.org/p/zrVlmktLyZu


请注意, 和xmlns:xsi只是xsi:type设置为显式属性名称,包括冒号。如您所见,如果在命名空间和属性名称之间留一个空格,encoding/xml 会进行更改以尝试清理输出中的命名空间(例如使用命名空间 URL 的最后一部分作为命名空间前缀:例如XMLSchema-instance) .


查看完整回答
反对 回复 2023-05-22
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信