亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Go 中,如何解析具有混合元素/chardata/elements/chardata

在 Go 中,如何解析具有混合元素/chardata/elements/chardata

Go
白豬掌柜的 2022-11-08 16:11:34
假設我有一個可以多次引用元素的結構:    <?xml version="1.0" encoding="UTF-8"?>    <book category="cooking">      <title>Everyday Italian</title>      <author>Giada De Laurentiis</author>      <year>2005</year>      <price>30.00</price>      Blah Blah Blah Bleh Blah of <year/> written by <author/>    </book>我如何解析這個 XML(或者更好地說,我如何描述結構),以便我可以擁有對它的這些內部引用?    type Book struct{       t string `xml:"book>title"`       p string `xml:"book>price"`       y string `xml:"book>year"`       a string `xml:"book>author"`       blah string ???????    }天真的方法(https://go.dev/play/p/JVM98pCcI0D),只是描述blah為cdata顯然是錯誤的,因為引用<year/>和<author/>正在丟失。在這里定義的正確方法是什么blah,使得它的內部結構,解析后仍然可用?
查看完整描述

1 回答

?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

基于icza評論的解決方案:


func (b *Book) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {

    for {

        t, err := d.Token()

        if err != nil {

            if err != io.EOF {

                return err

            }

            return nil

        }


        switch t := t.(type) {

        case xml.StartElement:

            var f interface{} // field

            var r string      // replace

            switch t.Name.Local {

            case "title":

                f = &b.Title

            case "author":

                if len(b.Author) > 0 { // if "author" was already decoded then assume this is the element in the "blah chardata"

                    r = b.Author // if you want <author/> to appear in Text then do `r = "<author/>"` instead

                } else {

                    f = &b.Author

                }

            case "year":

                if len(b.Year) > 0 { // same logic as for author above

                    r = b.Year

                } else {

                    f = &b.Year

                }

            case "price":

                f = &b.Price

            }

            if f != nil {

                if err := d.DecodeElement(f, &t); err != nil {

                    return err

                }

            }

            if len(r) > 0 {

                b.Text += " " + r + " " // add empty space for padding the replacement string

            }

        case xml.CharData:

            s := strings.TrimSpace(string(t))

            if len(s) > 0 {

                b.Text += s

            }

        }

    }

    return nil

}


查看完整回答
反對 回復 2022-11-08
  • 1 回答
  • 0 關注
  • 84 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號