dongzaheng4449 2017-09-13 18:36
浏览 65
已采纳

在golang中,如何编码包含空格的xml参数?

I have this xml api construct I need to use (this construct is not defined by me and I cannot change it):

<path><farmer id="ME7"/></path>

In go I have:

type Path struct {
  XMLName xml.Name `xml:"path"`
  FarmerId string `xml:"farmer id,attr"`
}

pMux := &Path{FarmerId: "ME7"}

However go encodes pMux and prints it as this:

<path xmlns:farmer="farmer" farmer:id="ME7" </path>

What I want is this:

<path><farmer id="ME7"/> </path>

How can I achieve this?

Thx

  • 写回答

2条回答 默认 最新

  • duanfu1942 2017-09-13 19:17
    关注

    The XML is invalid, but if you really need it to come out like that, use a regular expression to fix it afterward. Here is an example.

    I am assuming that you really want the open tag valid like so <path farmer id="ME7"></path>, instead of not having the open tag valid as you posted <path farmer id="ME7" </path>, but either way is doable with regex.

    BTW, your question is inconsistent about what you want. You start with wanting <path><farmer id="ME7"></path>, which @eugenioy 's answer will accommodate. Then end with "What I want is this: <path farmer id="ME7" </path>". Which my answer is geared toward.

    https://play.golang.org/p/A-sJhIgFZW

    package main
    
    import (
        "encoding/xml"
        "fmt"
        "regexp"
    )
    
    type Path struct {
        XMLName  xml.Name `xml:"path"`
        Farmer   string   `xml:"farmer,attr"`
        FarmerId string   `xml:"id,attr"`
    }
    
    func main() {
        path := &Path{
            FarmerId: "ME7",
        }
        data, err := xml.Marshal(path)
        if err != nil {
            fmt.Println(err)
            return
        }
    
        strData := string(data)
    
        // fix with regex
        reg := regexp.MustCompile(`(farmer)(="")`)
        strData = reg.ReplaceAllString(strData, "$1")
        fmt.Println(strData) // <path farmer id="ME7"></path>
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法