【问题标题】:XML Parsing GolangXML 解析 Golang
【发布时间】:2016-06-27 21:01:49
【问题描述】:

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

【问题讨论】:

  • 我认为您可以在 MixedVars 上实现自己的 Unmarshal 方法,但我不确定。还要检查一下,从 encoding/xml 的来源: /i> 可能有帮助
  • @plato 我试过使用 innerxml 但我仍然遇到类似的情况

标签: xml go


【解决方案1】:

可以一次将源 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。你应该很高兴从那里开始。

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多