来吧,encoding/xml:如何编组自闭元素? [英] Go, encoding/xml: How can I marshal self-closing elements?

查看:34
本文介绍了来吧,encoding/xml:如何编组自闭元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从以下结构编写XML:

I'm writing XML from the following struct:

type OrderLine struct {
    LineNumber     string `xml:"LineNumber"`
    Product        string `xml:"Product"`
    Ref            string `xml:"Ref"`
    Quantity       string `xml:"Quantity"`
    Price          string `xml:"Price"`
    LineTotalGross string `xml:"LineTotalGross"`
}

如果 Ref 字段为空,我希望显示该元素,但该元素会自动关闭,即

If the Ref field is empty, I'd like the element to display, but be self-closing, i.e.

<Ref />

不是:

<Ref></Ref>

AFAIK,这两个在语义上是等效的,但是我更喜欢一个自闭标签,因为它与其他系统的输出匹配.这可能吗?

AFAIK, these two are semantically equivalent, but I would prefer a self-closing tag, as it matches the output from other systems. Is this possible?

推荐答案

我找到了一种方法来黑客"元帅程序包,但是我没有对其进行测试.如果您想让我向您显示链接,请让我现在,然后将其发布在此回复的评论中.

I found a way to do it "hacking" marshal package, but I didn't test it. If you want me to show you the link, let me now, then I post it in comments of this reply.

我做了一些手动编码:

package main

import (
    "encoding/xml"
    "fmt"
    "regexp"
    "strings"
)

type ParseXML struct {
    Person struct {
        Name     string `xml:"Name"`
        LastName string `xml:"LastName"`
        Test     string `xml:"Abc"`
    } `xml:"Person"`
}

func main() {

    var err error
    var newPerson ParseXML

    newPerson.Person.Name = "Boot"
    newPerson.Person.LastName = "Testing"

    var bXml []byte
    var sXml string
    bXml, err = xml.Marshal(newPerson)
    checkErr(err)

    sXml = string(bXml)

    r, err := regexp.Compile(`<([a-zA-Z0-9]*)><(\\|\/)([a-zA-Z0-9]*)>`)
    checkErr(err)
    matches := r.FindAllString(sXml, -1)

    fmt.Println(sXml)

    if len(matches) > 0 {
        r, err = regexp.Compile("<([a-zA-Z0-9]*)>")
        for i := 0; i < len(matches); i++ {

            xmlTag := r.FindString(matches[i])
            xmlTag = strings.Replace(xmlTag, "<", "", -1)
            xmlTag = strings.Replace(xmlTag, ">", "", -1)
            sXml = strings.Replace(sXml, matches[i], "<"+xmlTag+" />", -1)

        }
    }

    fmt.Println("")
    fmt.Println(sXml)

}

func checkErr(chk error) {
    if chk != nil {
        panic(chk)
    }
}

这篇关于来吧,encoding/xml:如何编组自闭元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆