douran9707 2017-01-21 07:41
浏览 24

在Go中封送XML时如何保留标签的名称空间url

When I unmarshal and marshal this XML the URL for the namespace disappear:

<root xmlns:urn="http://test.example.com">
    <urn:copyright>tekst</urn:copyright>
</root>

Becomes:

<root xmlns:urn="">
    <urn:copyright></urn:copyright>
</root>

The code:

package main

import (
    "encoding/xml"
    "fmt"
)

type Root struct {
    XMLName      xml.Name     `xml:"root"`
    XmlNS        string       `xml:"xmlns:urn,attr"`
    Copyright    Copyright    `xml:"urn:copyright,omitempty"`
}

type Copyright struct {
    Text string `xml:",chardata"`
}

func main() {
    root := Root{}

    x := `<root xmlns:urn="http://test.example.com">
               <urn:copyright>text</urn:copyright>
          </root>`
    _ = xml.Unmarshal([]byte(x), &root)
    b, _ := xml.MarshalIndent(root, "", "    ")
    fmt.Println(string(b))
}

https://play.golang.org/p/1jSURtWuZO

  • 写回答

1条回答 默认 最新

  • dpqvwgr74759 2017-01-24 02:04
    关注

    Root.XmlNS isn't unmarshalled.

    "The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace name http://www.w3.org/2000/xmlns/." https://www.w3.org/TR/REC-xml-names/

    According to both the XML specification and the Go unmarshaling rules xml:"http://www.w3.org/2000/xmlns/ urn,attr" should work yet it doesn't. I don't think the maintainers will like the marshalling complexity that follows.

    You probably want to do the following.

        type Root struct {
            XMLName      xml.Name     `xml:"root"`
            Copyright    Copyright    `xml:"http://test.example.com copyright"`
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本