dssnh86244 2017-06-15 11:25 采纳率: 100%
浏览 46
已采纳

在动态结构元素上进行encoding / xml解组

I'm working with epubs using Golang, I have to fetch the cover image from cover.xhtml file (or whatever file it is mentioned in .opf file).

My problem is with dynamic structure of elements in the Cover.xhtml files.

Each epubs has different structure on the Cover.xhtml file. For example,

<body>
    <figure id="cover-image">
        <img src="covers/9781449328030_lrg.jpg" alt="First Edition" />
    </figure>
</body>

Another epub cover.xhtml file

<body>
    <div>
        <img src="@public@vhost@g@gutenberg@html@files@54869@54869-h@images@cover.jpg" alt="Cover" />
    </div>
</body>

I need to fetch the img tag's src attribute from this file. But I couldn't do it.

Here is the part of my Code that deals with unmarshalling the cover.xhtml file

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)

The output is:

{{}}

The output I'm expecting is:

{{covers/9781449328030_lrg.jpg}}

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doubianxian6557 2017-06-15 12:35
    关注

    This will pull out the img element from the read in file and then unmarshal the src attribute from the element. This is making the assumption that you will only ever need to grab the first img element from the file.

    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)
    

    This will produce the result of {covers/9781449328030_lrg.jpg} for the first input file and {@public@vhost@g@gutenberg@html@files@54869@54869-h@images@cover.jpg} for the second input file you provided.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示