XML 解析 Golang

标签 xml go

场景: 我有一个要解析的 XML 结构,我不知道如何设置一个结构,其中 xml 属性的值包含文本和更多嵌套值。所有其他属性都已正确设置,我不确定是否需要获取源的值并创建一个单独的解析器来检索元素的值。

<trans-unit id="some.message">
    <source>hello %<ph id="first_name">{0}</ph> %<ph id="last_name">{1}</ph>
    </source>
    <target/>
</trans-unit>

type TransUnit struct {
  Id string `xml:"id,attr"`
  Source string `xml:"source"`
  SourceVars MixedVars `xml:"source>ph"`
  Target string `xml:"target"`
}

type MixedVars []MixedVar

type MixedVar struct {
  VarName string `xml:"id,attr"`
}

编辑: 我正在尝试将源解析为遵循以下形式的字符串: 你好 %{first_name} %{last_name}

用当前结构解码 xml 字符串返回一个空结构

@plato 使用 innerxml 将源设置为:

<source>Are you sure you want to reset the reservation for %<ph id="first_name">{0}</ph> %<ph id="last_name">{1}</ph>

这让我处于类似的情况,我仍然在源值中插入了嵌套的 xml 标签

最佳答案

可以同时将源 xml 节点解码为原始 xml 和一片变量,例如:

type TransUnit struct {
    ID     string `xml:"id,attr"`
    Source Source `xml:"source"`
    Target string `xml:"target"`
}

type Source struct {
    Raw  string `xml:",innerxml"`
    Text string `xml:",chardata"`
    Vars []Var  `xml:"ph"`
}

type Var struct {
    ID    string `xml:"id,attr"`
    Value string `xml:",innerxml"`
}

查看 running example .你应该从那里开始。

关于XML 解析 Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38063179/

相关文章:

java - Android Xml 处理程序仅保留我的 xml 文件中的最后一个对象

xml - jetty 配置:dtd问题

go - 在golang中迭代Struct(映射键)值

go - 如何调用在根包上声明的变量

go - 是否有一个包可以在 golang 中编码进出 x-www-form-urlencoded

java - 如何使用 Framework Simple 将数据映射到正确的继承类

xml - 使用 XSLT,如何在我的两个 XML 元素之间显示一个空格? &nbsp 和间距不修复它

java - 在 android studio 项目中显示文本

Golang crypto/sha256 - 相同的输入产生不同的输出

go - go get 的 TLS 问题