在Golang中解码XML时自定义字符串转换

时间:2016-05-31 18:05:57

标签: xml go xml-parsing

我正在解码一些只包含字符串值和属性的XML。它还包含一些"&"的实例,这是不幸的,我想将其解码为"&"而不是"&"。我还将使用这些字符串值进行更多工作,我需要将字符"|"永远不会出现,因此我想用"|"替换任何"%7C"实例

我可以在解码后使用strings.Replace进行这些更改,但由于解码已经在进行类似的工作(毕竟它会将"&"转换为"&")我想同时做。

我要解析的文件很大,所以我会做类似于http://blog.davidsingleton.org/parsing-huge-xml-files-with-go/的文件

这是一个简短的示例xml文件:

<?xml version="1.0" encoding="utf-8"?>
<tests>
    <test_content>X&amp;amp;Y is a dumb way to write XnY | also here's a pipe.</test_content>
    <test_attr>
      <test name="Normal" value="still normal" />
      <test name="X&amp;amp;Y" value="should be the same as X&amp;Y | XnY would have been easier." />
    </test_attr>
</tests>

一些Go代码执行标准解码并打印出结果:

package main

import (
    "encoding/xml"
    "fmt"
    "os"
)

type XMLTests struct {
    Content string     `xml:"test_content"`
    Tests   []*XMLTest `xml:"test_attr>test"`
}

type XMLTest struct {
    Name  string `xml:"name,attr"`
    Value string `xml:"value,attr"`
}

func main() {
    xmlFile, err := os.Open("test.xml")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer xmlFile.Close()

    var q XMLTests

    decoder := xml.NewDecoder(xmlFile)

    // I tried this to no avail:
    // decoder.Entity = make(map[string]string)
    // decoder.Entity["|"] = "%7C"
    // decoder.Entity["&amp;amp;"] = "&"

    var inElement string
    for {
        t, _ := decoder.Token()
        if t == nil {
            break
        }
        switch se := t.(type) {
        case xml.StartElement:
            inElement = se.Name.Local
            if inElement == "tests" {
                decoder.DecodeElement(&q, &se)
            }
        default:
        }
    }

    fmt.Println(q.Content)
    for _, t := range q.Tests {
        fmt.Printf("\t%s\t\t%s\n", t.Name, t.Value)
    }
}

如何修改此代码以获得我想要的内容?即:如何自定义解码器?

我查看了文档,特别是https://golang.org/pkg/encoding/xml/#Decoder并尝试使用实体地图,但我无法取得任何进展。

修改

根据评论,我按照Multiple-types decoder in golang中的示例添加/更改了以下代码:

type string2 string

type XMLTests struct {
    Content string2    `xml:"test_content"`
    Tests   []*XMLTest `xml:"test_attr>test"`
}

type XMLTest struct {
    Name  string2 `xml:"name,attr"`
    Value string2 `xml:"value,attr"`
}

func (s *string2) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    var content string
    if err := d.DecodeElement(&content, &start); err != nil {
        return err
    }
    content = strings.Replace(content, "|", "%7C", -1)
    content = strings.Replace(content, "&amp;", "&", -1)
    *s = string2(content)
    return nil
}

适用于test_content但适用于属性?

X&Y is a dumb way to write XnY %7C also here's a pipe.
    Normal      still normal
    X&amp;Y     should be the same as X&Y | XnY would have been easier.

1 个答案:

答案 0 :(得分:1)

要处理属性,您可以将UnmarshalerAttr界面与UnmarshalXMLAttr方法一起使用。那么你的例子就变成了:

package main

import (
    "encoding/xml"
    "fmt"
    "strings"
)

type string2 string

type XMLTests struct {
    Content string2    `xml:"test_content"`
    Tests   []*XMLTest `xml:"test_attr>test"`
}

type XMLTest struct {
    Name  string2 `xml:"name,attr"`
    Value string2 `xml:"value,attr"`
}

func decode(s string) string2 {
    s = strings.Replace(s, "|", "%7C", -1)
    s = strings.Replace(s, "&amp;", "&", -1)
    return string2(s)
}

func (s *string2) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
    var content string
    if err := d.DecodeElement(&content, &start); err != nil {
        return err
    }
    *s = decode(content)
    return nil
}

func (s *string2) UnmarshalXMLAttr(attr xml.Attr) error {
    *s = decode(attr.Value)
    return nil
}

func main() {
    xmlData := `<?xml version="1.0" encoding="utf-8"?>
<tests>
    <test_content>X&amp;amp;Y is a dumb way to write XnY | also here's a pipe.</test_content>
    <test_attr>
      <test name="Normal" value="still normal" />
      <test name="X&amp;amp;Y" value="should be the same as X&amp;Y | XnY would have been easier." />
    </test_attr>
</tests>`
    xmlFile := strings.NewReader(xmlData)

    var q XMLTests

    decoder := xml.NewDecoder(xmlFile)
    decoder.Decode(&q)

    fmt.Println(q.Content)
    for _, t := range q.Tests {
        fmt.Printf("\t%s\t\t%s\n", t.Name, t.Value)
    }
}

输出:

X&Y is a dumb way to write XnY %7C also here's a pipe.
    Normal      still normal
    X&Y     should be the same as X&Y %7C XnY would have been easier.

(您可以在Go playground中进行测试。)

因此,如果在任何地方使用string2都适合你,那么这应该可以解决问题。

编辑:更简单的代码,不使用DecodeElement和类型切换......)