如何将空的 xmlns="" 添加到请求的结构标记中?

问题描述

你好,我是 golang 和编程的新手,我有一个菜鸟问题。我在谷歌上找不到答案。肥皂服务器因 gowsdl 生成代码而失败。但我将这个 xmlns="" 添加到 auth 标记它的作品就像一个魅力。那么我怎样才能将它添加标签中而不是通过字符串替换而是以惯用的方式呢?

服务器不接受


<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body xmlns="http://schemas.xmlsoap.org/soap/envelope/">
    <GetCitiesRequest xmlns="http://www.n11.com/ws/schemas">
        <auth>                     <<<<<<<<<<<<<<<<------------ fails because no xmlns=""
            <appKey>xxx</appKey>
            <appSecret>xx</appSecret>
        </auth>
    </GetCitiesRequest>
    </Body>
</Envelope>

服务器接受


 <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
    <Body>
        <GetCitiesRequest xmlns="http://www.n11.com/ws/schemas">
            <auth xmlns="">
                <appKey>[string]</appKey>
                <appSecret>[string]</appSecret>
            </auth>
        </GetCitiesRequest>
    </Body>
</Envelope>

我正在使用快速修复:

buffers := new(bytes.Buffer)
buffers.WriteString(strings.ReplaceAll(buffer.String(),"<auth>","<auth xmlns=\"\">"))

req,err := http.NewRequest("POST",s.url,buffers)

我应该添加什么结构标记来查看空的 xmlns="" ?

type GetCitiesRequest struct {
    XMLName xml.Name `xml:"http://www.n11.com/ws/schemas GetCitiesRequest"`

    Auth *Authentication `xml:"auth,omitempty" json:"auth,omitempty"`
}
type Authentication struct {
    AppKey string `xml:"appKey,omitempty" json:"appKey,omitempty"`

    AppSecret string `xml:"appSecret,omitempty" json:"appSecret,omitempty"`
}

阿洛斯我试过了;

type Authentication struct {
   XMLName xml.Name `xml:""`

   AppKey string `xml:"appKey,omitempty"`

   AppSecret string `xml:"appSecret,omitempty"`
}


   auth := Authentication{AppKey:"secret",AppSecret:"secret"}
   auth.XMLName.Local= "auth"
   auth.XMLName.Space = ""

我也试过 auth.XMLName.Space = " " 空格,但 xml.marshal 将其转换为转义字符,如 "&quote,#34"

我想了解如何使用专业方式而不是新手方式。 任何帮助表示赞赏。 谢谢。


一个问题:/未解决

试过 xml:"* categoryId" 结果 -> <categoryId xmlns="*">1001770</categoryId> 但是soap api不接受*字符想要<categoryId xmlns="">1001770</categoryId>

type Authentication struct {
    Xmlns string    `xml:"xmlns,attr"  json:"-"`
    AppKey string `xml:"appKey,omitempty"`
}

type GetSubCategoriesRequest struct {
    XMLName xml.Name `xml:"http://www.n11.com/ws/schemas GetSubCategoriesRequest"`

    Auth *Authentication `xml:"auth,omitempty"`

    CategoryId int64 `xml:"* categoryId,omitempty" json:"categoryId,omitempty"` <<<<<<<-------- i need xmlns="" 
}

有什么帮助吗?

解决方法

https://golang.org/pkg/encoding/xml/#Marshal

  • 带有“name,attr”标签的字段将成为 XML 元素中具有给定名称的属性。
  • 带有标记“,attr”的字段成为 XML 元素中带有字段名称的属性。
type Authentication struct {
    Xmlns     string `xml:"xmlns,attr" json:"-"`
    AppKey    string `xml:"appKey,omitempty" json:"appKey,omitempty"`
    AppSecret string `xml:"appSecret,omitempty" json:"appSecret,omitempty"`
}

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