dongmanzui8486 2017-08-19 10:26
浏览 80
已采纳

具有XML名称空间的属性

The following struct is used to marshall SAML XML elements such as OrganizationName, OrganizationDisplayName & OrganizationURL.

type LocalizedName struct {
    Lang  string `xml:"xml lang,attr"`
    Value string `xml:",chardata"`
}

The Lang attribute is within the xml namespace. The generated XML from the encoding/xml package includes relative namespaces:

<Organization>
  <OrganizationName xmlns:_xml="xml" _xml:lang="en">name</OrganizationName>
  <OrganizationDisplayName xmlns:_xml="xml" _xml:lang="en">name</OrganizationDisplayName>
  <OrganizationURL xmlns:_xml="xml" _xml:lang="en">http://www.example.com/</OrganizationURL>
</Organization>

I was expecting the elements to not use relative namespaces as they seem to be considered to be insecure, although I do not understand why:

<OrganizationName xml:lang="en">name</OrganizationName>

What causes the relative namespaces to be created?

  • 写回答

1条回答 默认 最新

  • dousi4900 2018-09-17 07:29
    关注

    if you want to generate something like this:

    <OrganizationName xml:lang="en">name</OrganizationName>
    

    you can use the following:

    package main
    
    import (
        "encoding/xml"
        "fmt"
    )
    
    //OrganizationName Name
    type OrganizationName struct {
        XMLName xml.Name `xml:"OrganizationName"`
        Lang    string   `xml:"http://www.w3.org/XML/1998/namespace lang,attr,omitempty"`
        Value   string   `xml:",chardata"`
    }
    
    //Organization Organization Entity
    type Organization struct {
        XMLName          xml.Name         `xml:"Organization"`
        OrganizationName OrganizationName `xml:"OrganizationName"`
    }
    
    func main() {
        v := Organization{
            OrganizationName: OrganizationName{
                Lang:  "en",
                Value: "Hisham Karam",
            },
        }
        output, err := xml.MarshalIndent(v, "  ", "    ")
        if err != nil {
            fmt.Printf("error: %v
    ", err)
        }
        fmt.Printf("
    %s", string(output))
    
    }
    

    output:

      <Organization>
          <OrganizationName xml:lang="en">Hisham Karam</OrganizationName>
      </Organization>
    

    go version:

    go version go1.10.3 darwin/amd64
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿