gpt4 book ai didi

xml - 通过 UnMarshal 和 MarshalIndent 往返 xml

转载 作者:IT王子 更新时间:2023-10-29 02:08:59 25 4
gpt4 key购买 nike

我想使用 golang 的 xml.MarshalIndent() 快速创建一个实用程序来格式化任何 XML 数据

但是this code

package main

import (
"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 lang="en">
<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> 之后的无关内容打开元素。

  • 我失去了我的属性 - 为什么?
  • 我想避免收集虚假的元素间字符数据 - 怎么做?

最佳答案

对于初学者来说,您没有正确使用属性结构标签,所以这是一个简单的解决方法。

来自 https://godoc.org/encoding/xml#Unmarshal

  • If the XML element has an attribute not handled by the previous rule and the struct has a field with an associated tag containing ",any,attr", Unmarshal records the attribute value in the first such field.

其次,因为标签 xml:",chardata" 甚至没有通过 xml.Unmarshaller 接口(interface)的 UnmarshalXML 传递该字段,您不能简单地为 Text 创建一个新类型并为它实现该接口(interface),如同一文档中所述。 (注意除了 []byte 或 string 之外的任何类型都会强制报错)

  • If the XML element contains character data, that data is accumulated in the first struct field that has tag ",chardata". The struct field may have type []byte or string. If there is no such field, the character data is discarded.

因此,处理不需要的字符的最简单方法是事后替换它们。

完整的代码示例在这里:https://play.golang.org/p/VSDskgfcLng

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])
}
}

理论上可以为 Node 实现 xml.Unmarshaller 接口(interface),但是你不仅要处理手动 xml 解析,而且它是一个递归结构。事后删除不需要的字符是最简单的。

关于xml - 通过 UnMarshal 和 MarshalIndent 往返 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52669545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com