You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Go解析EPUB的container.xml时无法获取rootfile属性值问题排查

Go解析EPUB容器XML获取rootfile属性失败的原因及修复

你的代码存在两个关键问题导致解析结果为空:

1. 未处理XML命名空间

原XML的<container>标签带有命名空间xmlns="urn:oasis:names:tc:opendocument:xmlns:container",Go的encoding/xml包要求结构体必须明确匹配命名空间才能正确解析对应节点,否则会忽略未匹配的元素。

2. 结构体层级与XML结构不匹配

原XML的层级是container -> rootfiles -> rootfile,但你的代码直接尝试将整个XML解析到RootFile结构体,跳过了外层的container和rootfiles节点,导致解析器无法定位到目标<rootfile>元素。

修复后的完整代码

package main

import (
    "fmt"
    "encoding/xml"
)

// 匹配带命名空间的根节点container
type Container struct {
    XMLName xml.Name `xml:"urn:oasis:names:tc:opendocument:xmlns:container container"`
    RootFiles RootFiles `xml:"rootfiles"`
}

// 对应XML中的rootfiles节点
type RootFiles struct {
    RootFile RootFile `xml:"rootfile"`
}

// 对应rootfile节点的属性
type RootFile struct {
    FullPath  string `xml:"full-path,attr"`
    MediaType string `xml:"media-type,attr"`
}

func main() {
    xmlData := `
    <?xml version="1.0" encoding="UTF-8"?>
    <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
        <rootfiles>
            <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
       </rootfiles>
    </container>
    `

    var container Container
    err := xml.Unmarshal([]byte(xmlData), &container)
    if err != nil {
        fmt.Printf("解析错误: %v\n", err)
        return
    }
    fmt.Println(container.RootFiles.RootFile)
}

代码说明

  • 通过Container结构体的XMLName标签明确匹配带命名空间的<container>根节点
  • 新增RootFiles结构体对应XML中的<rootfiles>节点,补全层级结构
  • RootFile结构体的属性标签保持不变,现在可以正确映射到<rootfile>的属性值

执行修复后的代码,会输出预期结果:

{OEBPS/content.opf application/oebps-package+xml}

内容的提问来源于stack exchange,提问作者anewb33

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 12:43:28