在 go 中使用 `encoding/xml` 解析含嵌套 html 标签的 xml 字段时,默认会忽略标签、仅提取纯文本;需使用 `xml:",innerxml"` 标签显式捕获原始 xml/html 片段。
Go 的标准库 encoding/xml 在解析结构体字段时,默认行为是跳过子元素标签,只提取其字符数据(text content)。因此,当 XML 中
要完整保留原始 HTML 片段(包括标签、属性、嵌套结构和空白),必须使用特殊的 struct tag:xml:",innerxml"。它告诉解码器将该字段对应 XML 元素的全部内部 XML 字节流(不含起始/结束标签本身) 直
接赋值为字符串。
以下是修正后的完整示例:
package main
import (
"encoding/xml"
"fmt"
)
type ResultSlice struct {
MyText []Result `xml:"results>result"`
}
type Result struct {
Text struct {
HTML string `xml:",innerxml"` // ✅ 关键:捕获 内所有原始内容
} `xml:"text"`
}
func main() {
s := `
This has styleThen some not-style
No style here
Again, no style
`
r := &ResultSlice{}
if err := xml.Unmarshal([]byte(s), r); err != nil {
fmt.Fatalf("XML unmarshal error: %v", err)
}
for i, res := range r.MyText {
fmt.Printf("Result %d: %q\n", i+1, res.Text.HTML)
}
} 输出结果为:
Result 1: "This has styleThen some not-style" Result 2: "No style here" Result 3: "Again, no style"
⚠️ 注意事项:
总结:xml:",innerxml" 是 Go 解析混合 HTML/XML 数据的必备技巧——它放弃语义解析,转而提供字节级控制权,是兼顾简洁性与准确性的标准实践。