使用golang解析tei XML 使用golang编写代码来解析tei XML。

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

Parsing a tei XML with golang

问题

我需要使用golang解析一个tei XML文件。我尝试使用encoding/xml的解组器。这里是一个例子:http://play.golang.org/p/h0k-4IjngY

问题:

  1. 即使tei文件无效,xml文件有效,这个例子也没有返回任何内容。如果我删除第23行的<TEI>(使xml文件无效),这个例子就会打印出一些内容。
  2. 如何使Line结构体包含<l>元素的内容?
  3. 在Page结构体中,我需要n属性的值,我该如何实现?

解组是解析这种文件的正确方法,还是nokogiri会是更好的解决方案?

谢谢。

英文:

I need to parse a tei XML file with golang. I tried using the encoding/xml unmarshaller. Here is the example:
http://play.golang.org/p/h0k-4IjngY

Problems:

  1. Even if tei file is not valid and the xml is valid the example returns me nothing. If I remove line 23 <TEI> (so xml is not anymore valid), the example prints something.
  2. How can I have the Line struct a string containing the content of <l> element?
  3. In the Page struct I need the value of n attribute, how do I achieve this?

Is unmarshalling the right way to parse these kinds of files or nokogiri would be a better solution?

Thanks

答案1

得分: 0

使用xml.Unmarshal()函数读取这个XML是完全可以的。

问题在于XML的结构如下:

<TEI>
	<text>
		<sp>
		</sp>
		<sp>
		</sp>
	</text>
</TEI>

而你的Go结构如下:

Page
	[]Speak

缺少一层。 你的Page可能匹配<TEI><text>元素,但不能同时匹配两者。如果删除<TEI>元素,它可以匹配<text>及其内容。

解决方案:

添加另一个包装器,如下所示:

type Text struct {
	Txt Page `xml:"text"`
}

当然,解析时要使用这种类型的值:

var p Text
err := xml.Unmarshal([]byte(data), &p)

Go Playground上尝试修改后的代码。

英文:

It is perfectly fine to read this XML using xml.Unmarshal().

The problem is that the XML structure is the following:

<TEI>
	<text>
		<sp>
		</sp>
		<sp>
		</sp>
	</text>
</TEI>

And your Go structure is the following:

Page
	[]Speak

There is one missing layer. Your Page might match the <TEI> or <text> element, but not both. It works for you if you remove the <TEI> element because then Page can match <text> and its contents.

Solution:

Add another wrapper like this:

type Text struct {
	Txt Page `xml:"text"`
}

And of course parse a value of this type:

var p Text
err := xml.Unmarshal([]byte(data), &p)

Try it your modified code on the Go Playground.

huangapple
  • 本文由 发表于 2015年3月2日 22:12:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/28811899.html
匿名

发表评论

匿名网友

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

确定