xml - 在 Go 中编码元素中的任意 XML 属性?

标签 xml go

我需要在运行时在元素上编码额外的属性。我试过这个:

type Meh struct {
    XMLName xml.Name
    Attrs []xml.Attr
}

Meh{
    Attrs: []xml.Attr{
        xml.Attr{xml.Name{Local: "hi"}, "there"},
    },  
}

但是字段被视为新元素:

<Meh><Attrs><Name></Name><Value>there</Value></Attrs></Meh>

如果我将标签 xml:",attr" 添加到 Attr 字段,它需要一个 []byte string 指定单个属性的内容。

如何在运行时指定属性?如何注释类型以为此提供字段?

最佳答案

您可以尝试直接使用模板。示例:

package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
    "text/template"
)

type ele struct {
    Name  string
    Attrs []attr
}

type attr struct {
    Name, Value string
}

var x = `<{{.Name}}{{range $a := .Attrs}} {{$a.Name}}="{{xml $a.Value}}"{{end}}>
</{{.Name}}>`

func main() {
    // template function "xml" defined here does basic escaping,
    // important for handling special characters such as ".
    t := template.New("").Funcs(template.FuncMap{"xml": func(s string) string {
        var b bytes.Buffer
        xml.Escape(&b, []byte(s))
        return b.String()
    }})
    template.Must(t.Parse(x))
    e := ele{
        Name: "Meh",
        Attrs: []attr{
            {"hi", "there"},
            {"um", `I said "hello?"`},
        },
    }
    b := new(bytes.Buffer)
    err := t.Execute(b, e)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(b)
}

输出:

<Meh hi="there" um="I said &#34;hello?&#34;">
</Meh>

关于xml - 在 Go 中编码元素中的任意 XML 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10828187/

相关文章:

memory-leaks - channel 和内存泄漏

go - 如何在 Golang 中对 URL 进行插值

xml - XSLT——将文本节点的值解释为 XPath 查询(并在转换中使用它)

xml - 使用 Perl 解析 XML 中嵌套属性的最佳方法是什么?

xml - Perl 探查器中断对 XML 解析器的调用

string - 在 Go 中获取最多 N 个字符/元素的子字符串/子 slice 的简单方法

javascript - 如何在 Golang 请求中执行 javascript 异步代码

java - Stax 将 Text+CDATA+Text 视为单个 CHARACTERS 部分

c# - 无需 Linq 即可解析和访问 XML

go - 如何通过登录将 session 数据存储在 chi 路由器上下文中