我正在使用Golang处理epubs,我必须从cover.xhtml文件(或.opf文件中提到的任何文件(中获取封面图像。
我的问题是封面文件中元素的动态结构.xhtml。
每个 epubs 在封面.xhtml文件上都有不同的结构。例如
<body>
<figure id="cover-image">
<img src="covers/9781449328030_lrg.jpg" alt="First Edition" />
</figure>
</body>
另一个 epub 封面.xhtml文件
<body>
<div>
<img src="@public@vhost@g@gutenberg@html@files@54869@54869-h@images@cover.jpg" alt="Cover" />
</div>
</body>
我需要从这个文件中获取 img 标签的 src 属性。但我做不到。
这是我的代码中处理解组封面.xhtml文件
的部分type CPSRCS struct {
Src string `xml:"src,attr"`
}
type CPIMGS struct {
Image CPSRCS `xml:"img"`
}
XMLContent, err = ioutil.ReadFile("./uploads/moby-dick/OPS/cover.xhtml")
CheckError(err)
coverFile := CPIMGS{}
err = xml.Unmarshal(XMLContent, &coverFile)
CheckError(err)
fmt.Println(coverFile)
输出为:
{{}}
我期望的输出是:
{{covers/9781449328030_lrg.jpg}}
提前感谢!
这将从读入文件中提取img
元素,然后从元素中取消封送 src 属性。这是假设您只需要从文件中获取第一个img
元素。
XMLContent, err = ioutil.ReadFile("./uploads/moby-dick/OPS/cover.xhtml")
CheckError(err)
//Parse the XMLContent to grab just the img element
strContent := string(XMLContent)
imgLoc := strings.Index(strContent, "<img")
prefixRem := strContent[imgLoc:]
endImgLoc := strings.Index(prefixRem, "/>")
//Move over by 2 to recover the '/>'
trimmed := prefixRem[:endImgLoc+2]
var coverFile CPSRCS
err = xml.Unmarshal([]byte(trimmed), &coverFile)
CheckError(err)
fmt.Println(coverFile)
这将为第一个输入文件生成 {covers/9781449328030_lrg.jpg} 的结果,为提供的第二个输入文件生成 {@public@vhost@g@gutenberg@html@files@54869@54869-h@images@cover.jpg} 的结果。