去xml解组

有没有一种方法可以仅使用一个结构(带有encode/xml)来提取HTML文件中的图像源?现在我有这样的东西


type XML struct {

    A Image `xml:"div>img"`

}


type Image struct {

    I string `xml:"src,attr"`

}

只声明像这样的东西会很棒:


type Image struct {

    I string `xml:"div>img,src,attr"`

}

这是HTML:


<div><div><img src="hello.png"/></div></div>


忽然笑
浏览 166回答 1
1回答

泛舟湖上清波郎朗

似乎一个好方法是使用该exp/html软件包,如下所示:package mainimport (&nbsp; &nbsp; "exp/html"&nbsp; &nbsp; "strings")func main() {&nbsp; &nbsp; a, _ := html.Parse(strings.NewReader(testString))&nbsp; &nbsp; println(a.FirstChild.FirstChild.NextSibling.FirstChild.FirstChild.FirstChild.Attr[0].Val)}var testString = `<div><div><img src="hello.png"/></div></div>`所有这一切都FirstChild和NextSibling需要,因为exp/html构建一个“正确”的HTML5树所以这段代码实际上是解析如下:<html>&nbsp; &nbsp; <head></head>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="hello.png"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go