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

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

通過 UnMarshal 和 MarshalIndent 往返 xml

通過 UnMarshal 和 MarshalIndent 往返 xml

Go
揚帆大魚 2023-04-17 16:29:52
我想使用 golang 的 xml.MarshalIndent() 快速創建一個實用程序來格式化任何 XML 數據然而這段代碼package mainimport (    "encoding/xml"    "fmt")func main() {    type node struct {        XMLName  xml.Name        Attrs    []xml.Attr `xml:",attr"`        Text     string     `xml:",chardata"`        Children []node     `xml:",any"`    }    x := node{}    _ = xml.Unmarshal([]byte(doc), &x)    buf, _ := xml.MarshalIndent(x, "", "  ") // prefix, indent    fmt.Println(string(buf))}const doc string = `<book>     <title>The old man and the sea</title>       <author>Hemingway</author></book>`產品<book>&#xA;     &#xA;       &#xA;  <title>The old man and the sea</title>  <author>Hemingway</author></book>請注意打開元素后的外來物質<book>。我失去了我的屬性 - 為什么?我想避免收集虛假的元素間字符數據 - 怎么做?
查看完整描述

1 回答

?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

對于初學者,您沒有正確使用屬性 struct 標簽,所以這是一個簡單的解決方法。

  • 如果 XML 元素具有先前規則未處理的屬性,并且結構具有包含“,any,attr”的關聯標記的字段,則 Unmarshal 會在第一個此類字段中記錄屬性值。

其次,因為標記xml:",chardata"甚至不通過接口傳遞該字段UnmarshalXMLxml.Unmarshaller所以您不能簡單地為它創建一個新類型Text并為它實現該接口,如同一文檔中所述。(注意除 []byte 或 string 以外的任何類型都會強制報錯)

  • 如果 XML 元素包含字符數據,則該數據將累積在具有標記“,chardata”的第一個結構字段中。struct 字段的類型可以是 []byte 或 string。如果沒有這樣的字段,字符數據將被丟棄。

因此,處理不需要的字符的最簡單方法是在事后替換它們。

var Replacer = strings.NewReplacer("&#xA;","","&#x9;","","\n","","\t","")


func recursiveReplace(n *Node) {

? ? n.Text = Replacer.Replace(n.Text)

? ? for i := range n.Children {

? ? ? ? recursiveReplace(&n.Children[i])

? ? }

}

理論上可以實現xml.Unmarshaller的接口Node,但是您不僅要處理手動 xml 解析,還要處理它是遞歸結構這一事實。事后刪除不需要的字符是最簡單的。


查看完整回答
反對 回復 2023-04-17
  • 1 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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