duanbixia7738 2016-06-27 21:01
浏览 33
已采纳

XML解析Golang

Scenario: I have an XML structure I'm trying to parse, I don't know how to set up a struct where the value of an xml attribute contains text and more nested values. All other attributes have been set properly, I'm not sure if I'll need to get the value of the source and create a separate parser to retrieve the values of the elements.

<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"`
}

EDIT: I'm trying to parse the source into a string that follows the form: hello %{first_name} %{last_name}

Unmarshalling the xml string with the current structs returns a an empty struct

@plato using innerxml sets the source to:

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

This puts me in a similar situation where I still have nested xml tags interpolated within the source value

  • 写回答

1条回答 默认 最新

  • doumeng06063991 2016-06-28 23:12
    关注

    It's possible to unmarshal the source xml node into both the raw xml and a slice of variables at once, eg:

    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"`
    }
    

    See a running example. You should be good to go from there.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改