英文:
Unmarshal XML preserving child elements
问题
以下是您提供的代码的翻译:
package main
import (
"encoding/xml"
"log"
)
func main() {
xmltext := []byte(`<Root><Foo>text text text <a href="url">foo bar</a> and more text.</Foo></Root>`)
type mystruct struct {
Foo string `xml:",innerxml"`
}
v := &mystruct{}
err := xml.Unmarshal(xmltext, v)
if err != nil {
log.Fatal(err)
}
log.Println(v.Foo)
}
您想要在解组时保留某个 XML 标签中的子元素。当前的结果是:
<Foo>text text text <a href="url">foo bar</a> and more text.</Foo>
但是您想要获取的结果是:
text text text <a href="url">foo bar</a> and more text.
即:您想要保留元素 Foo 的“字符串值”(不是 XPath 意义上的字符串值)。
您如何在不包含 <Foo>
和 </Foo>
的情况下获取元素 Foo 的内容?
英文:
Code at http://play.golang.org/p/PlOMw4wfT2
I'd like to preserve the child elements in some XML tag when unmarshalling. This is my code:
package main
import (
"encoding/xml"
"log"
)
func main() {
xmltext := []byte(`<Root><Foo>text text text <a href="url">foo bar</a> and more text.</Foo></Root>`)
type mystruct struct {
Foo string `xml:",innerxml"`
}
v := &mystruct{}
err := xml.Unmarshal(xmltext, v)
if err != nil {
log.Fatal(err)
}
log.Println(v.Foo)
}
and the result is:
<Foo>text text text <a href="url">foo bar</a> and more text.</Foo>
but I'd like to get
text text text <a href="url">foo bar</a> and more text.
(without the surrounding Foo-tags)
That is: I want to preserve the "string value" (not the string value in the XPath sense) of the element Foo.
How can I get the contents from the element Foo without the <Foo>
and </Foo>
?
答案1
得分: 1
,innerxml
包含XML标签的内容(这就是它的名称所指的)。因此,我需要再深入一层:
package main
import (
"encoding/xml"
"log"
)
func main() {
xmltext := []byte(`<Root><Foo>text text text <a href="url">foo bar</a> and more text.</Foo></Root>`)
type text struct {
Text string `xml:",innerxml"`
}
type mystruct struct {
Foo text
}
v := &mystruct{}
err := xml.Unmarshal(xmltext, v)
if err != nil {
log.Fatal(err)
}
log.Println(v.Foo.Text)
// text text text <a href="url">foo bar</a> and more text.
}
英文:
The ,innerxml
contains the contents of the XML tag (that's what it's name is about). Therefore I have to go one level deeper:
<!-- language: lang-go -->
package main
import (
"encoding/xml"
"log"
)
func main() {
xmltext := []byte(`<Root><Foo>text text text <a href="url">foo bar</a> and more text.</Foo></Root>`)
type text struct {
Text string `xml:",innerxml"`
}
type mystruct struct {
Foo text
}
v := &mystruct{}
err := xml.Unmarshal(xmltext, v)
if err != nil {
log.Fatal(err)
}
log.Println(v.Foo.Text)
// text text text <a href="url">foo bar</a> and more text.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论