场景: 我有一个要解析的 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/