解析 XML 中的 innerXml 和其属性。

huangapple go评论87阅读模式
英文:

xml Unmarshal innerXml and its attributes

问题

我想要解析innerXml及其属性。我编写了一个Unmarshal函数来实现这个功能,但是看起来函数进入了一个无限循环。错误信息如下:

runtime: goroutine stack exceeds 1000000000-byte limit 
fatal error: stack overflow

示例代码在这里

我不知道为什么会出现这个问题。有人可以帮助我吗?谢谢。

更新1:感谢Ainar-G。我尝试了他的示例,它可以将innerXml作为chardata获取,这是我没有发现的。如果我将示例更改为这个,结果是空的,它应该包含<c>中的所有原始xml。

更新2:我找到了一个解决方案,但可能有点冗长。代码在这里

英文:

I want to Unmarshal the innerXml and its attributes. I write a Unmarshal function to implement this, but it looks like the function is in an infinite loop. The error information is

runtime: goroutine stack exceeds 1000000000-byte limit 
fatal error: stack overflow

The example is here.

I don't know why this happens. Could someone help me, thanks.

Update1: Thanks Ainar-G. I tried his example. It works as get the innerXml as chardata which I did't find. If I change the example as this, the result is empty, it should include all the raw xml in <c>.

Update2: I find a solution, but may be a little wordy. code.

答案1

得分: 2

在你的UnmarshalXML方法中,你调用了xml.(*Decoder).DecodeElement,而DecodeElement又会调用UnmarshalXML,这样就创建了一个无限循环。你可以创建一个包装结构体,或者在UnmarshalXML中只解析你结构体的一部分。

**编辑:**如果你想解析节点的所有属性,请参考这个答案中的示例。

工作示例:

func (in *innerXml) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    in.XMLName = start.Name
    in.Attrs = make(map[string]string)
    for _, attr := range start.Attr {
        in.Attrs[attr.Name.Local] = attr.Value
    }
    
    err := d.DecodeElement(&in.Value, &start)
    if err != nil {
        return err
    }

    return nil
}

在线示例:http://play.golang.org/p/TLcqFSyn94

英文:

In your UnmarshalXML method you call xml.(*Decoder).DecodeElement, which in turn calls UnmarshalXML, etc. This creates the infinite loop. Either create a wrapper struct, or unmarshal only a part of your struct in your UnmarshalXML.

EDIT: if you want to unmarshal all attributes of a node, see the example in this answer.

Working example:

func (in *innerXml) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	in.XMLName = start.Name
	in.Attrs = make(map[string]string)
	for _, attr := range start.Attr {
		in.Attrs[attr.Name.Local] = attr.Value
	}
	
	err := d.DecodeElement(&amp;in.Value, &amp;start)
	if err != nil {
		return err
	}

	return nil
}

Playground: http://play.golang.org/p/TLcqFSyn94

huangapple
  • 本文由 发表于 2015年5月17日 18:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/30285759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定