XML解析Golang [英] XML Parsing Golang

查看:428
本文介绍了XML解析Golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:
我有一个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>

类型TransUnit结构{
Id字符串`xml:id,attr`
源字符串`xml:source`
SourceVars MixedVars`xml: source> ph`
目标字符串`xml:target`
}

类型MixedVars [] MixedVar

类型MixedVar结构{
VarName字符串`xml:id,attr`
}

编辑:
我试图将源代码解析为如下形式的字符串:
hello%{first_name}%{last_name}



使用当前结构解组xml字符串会返回一个空的结构<​​/ p>

使用innerxml将源设置为:
$您确定要为%< ph id =first_name> {0}< / ph>< %< ph id =last_name> {1}< / ph>





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

解决方案

有可能将源xml节点解组为原始xml和一片变量,例如:

  type TransUnit struct {
ID string`xml:id ,attr`
来源`xml:source`
目标字符串`xml:target`
}

类型来源结构{
原始字符串`xml:,innerxml`
文本字符串`xml:,chardata`
Vars [] Var`xml:ph`
}

类型Var结构{
ID字符串`xml:id,attr`
值字符串`xml:,innerxml`
}

查看运行示例。你应该很好从那里去。


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

解决方案

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.

这篇关于XML解析Golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆