猿问

如何将字符串转换为 XML

我有一个字符串格式的 XML,有人可以帮我将 XML 字符串转换为正确的 XML 格式吗?


package main


import "fmt"


func main() {


    message := `<?xml proflie ><test> value '123'</test>`

    fmt.Printf("%s", message)

}


繁星点点滴滴
浏览 353回答 1
1回答

芜湖不芜

使用encoding/xml具有以下EscapeText功能的包:package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt")func Xml(in string) string {&nbsp; &nbsp; var b bytes.Buffer&nbsp; &nbsp; xml.EscapeText(&b, []byte(in))&nbsp; &nbsp; return b.String()}func main() {&nbsp; &nbsp; fmt.Println(`<?xml profile><test>` + Xml(`test '123'`) + `</test>`)}这将产生输出:test &#39;123&#39;Go 在包中对 XML 有很好的支持encoding/xml,还有其他方法可以生成输出,而不涉及手动构建 XML。此版本在<test>元素中进行包装,还允许您将 an 传递interface{}给EncodeElement方法,因此您不仅限于字符串:package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "os")func main() {&nbsp; &nbsp; s := `test '123'`&nbsp; &nbsp; test := xml.StartElement{Name:xml.Name{Local:`test`}}&nbsp; &nbsp; xml.NewEncoder(os.Stdout).EncodeElement(s, test)}最后,也许是最好的,这个版本使用 astuct和.Encode方法:package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "os")type Test struct {&nbsp; &nbsp; XMLName xml.Name `xml:"test"`&nbsp; &nbsp; Content string `xml:",chardata"`}func main() {&nbsp; &nbsp; s := Test{Content:`test '123'`}&nbsp; &nbsp; xml.NewEncoder(os.Stdout).Encode(&s)}现在您可以扩展该结构,但最重要的是,您还可以Unmarshal或Decode这种类型,从传入的 XML 中提取数据:package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt")type Test struct {&nbsp; &nbsp; XMLName xml.Name `xml:"test"`&nbsp; &nbsp; Content string `xml:",chardata"`}func main() {&nbsp; &nbsp; s := Test{Content:`test '123'`}&nbsp; &nbsp; var buf bytes.Buffer&nbsp; &nbsp; xml.NewEncoder(&buf).Encode(&s)&nbsp; &nbsp; fmt.Println("Encoded =", buf.String())&nbsp; &nbsp; var read Test&nbsp; &nbsp; xml.NewDecoder(bytes.NewReader(buf.Bytes())).Decode(&read)&nbsp; &nbsp; fmt.Println("Content =", read.Content)}xml.Marshal有关xml 包支持的标签的完整描述,请参阅文档: https ://golang.org/pkg/encoding/xml/#Marshal
随时随地看视频慕课网APP

相关分类

Go
我要回答