Purpose:我有一个包含大量混合内容CDATA元素的XML文档,需要以编程方式对其进行编辑.令人恼火的是,因为CDATA元素有其他/混合内容,默认的",CDATA"标记不能正常工作(根据XML规范).如果你有关于这方面的细节的问题,请让我知道.

Issue:在下面的简化示例中,我将其中带有CDATA的元素标记为",innerxml",以便自己处理前缀/后缀.对于解组,一切都按预期工作,但是使用编组(编码)时,特殊字符被转义.为什么EncodeElement方法在标记明确表示不要转义特殊字符时对其进行转义(通过",innerxml"标记)?当我在文档中读到此方法时,它向我推荐了xml.Marshal方法,其中显示了以下内容:

带有",innerxml"标记的字段是逐字写入的,不遵循通常的封送处理过程.

Example:

以下是代码(也可以在https://go.dev/play/p/MH_ONAVaG_1处获得):

package main

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

var xmlFile string = `<?xml version="1.0" encoding="UTF-8"?>
<statusdb>
  <status date="today">
      <![CDATA[today is < yesterday]]>
  </status>
  <status  date="yesterday">
      <![CDATA[PM,
      1. there are issues with the marshaller
      2. i don't know how to solve them]]>
  </status>
</statusdb>`

type statusDB struct {
    Status []*status `xml:"status"`
}

type status struct {
    Text string `xml:",innerxml"`
    Date string `xml:"date,attr"`
}

type statusMarshaller status

func main() {

    var projectStatus statusDB

    err := xml.Unmarshal([]byte(xmlFile), &projectStatus)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("In Go: \"" + projectStatus.Status[0].Text + "\"")
    fmt.Println("In Go: \"" + projectStatus.Status[1].Text + "\"")
    x, err := xml.MarshalIndent(projectStatus, "", "  ")
    if err != nil {
        fmt.Println(err)
        return
    }
    //why this is not printing properly
    fmt.Printf("%s\n", x)
}

func (tagElement *status) UnmarshalXML(d *xml.Decoder, se xml.StartElement) error {
    temp := statusMarshaller{}
    d.DecodeElement(&temp, &se)
    temp.Text = strings.TrimSpace(temp.Text)
    temp.Text = strings.TrimPrefix(temp.Text, "<![CDATA[")
    temp.Text = strings.TrimSuffix(temp.Text, "]]>")
    *tagElement = status(temp)
    return nil
}

func (tagElement status) MarshalXML(d *xml.Encoder, se xml.StartElement) error {
    tagElement.Text = "<![CDATA[" + tagElement.Text + "]]>"
    temp, _ := xml.Marshal(statusMarshaller(tagElement))
    return d.EncodeElement(temp, se)
}

此代码返回以下内容:

In Go: "today is < yesterday"
In Go: "PM,
      1. there are issues with the marshaller
      2. i don't know how to solve them"
<statusDB>
  <status>&lt;statusMarshaller date=&#34;today&#34;&gt;&lt;![CDATA[today is &lt; yesterday]]&gt;&lt;/statusMarshaller&gt;</status>
  <status>&lt;statusMarshaller date=&#34;yesterday&#34;&gt;&lt;![CDATA[PM,&#xA;      1. there are issues with the marshaller&#xA;      2. i don&#39;t know how to solve them]]&gt;&lt;/statusMarshaller&gt;</status>
</statusDB>

Program exited.

Conclusion:请解释一下XML包为什么要这样做,以及可能的解决方法是什么?

谢谢!

推荐答案

当然,如果包中的CDATA允许混合元素,那就更好了,但现在我已经找到了解决方法,即上面的代码,只做了一点小改动,不对marhshalXML函数中的statusMarshaller类型调用‘marshal’.相反,我只将tag Element转换为statusMarshaller类型,然后对该元素进行编码.详情见下文:

修订历史:

  1. 修改了marshalXML函数中的第二行,删除了对xml.marshal的调用
  2. 我修改了status struct 以包含XMLName成员,从而维护XML元素名称(在生成的xml元素中保留"status"而不是"statusMarshaller
package main

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

var xmlFile string = `<?xml version="1.0" encoding="UTF-8"?>
<statusdb>
  <status date="today">
      <![CDATA[today is < yesterday]]>
  </status>
  <status  date="yesterday">
      <![CDATA[PM,
      1. there are issues with the marshaller
      2. i don't know how to solve them]]>
  </status>
</statusdb>`

type statusDB struct {
    Status []*status `xml:"status"`
}

type status struct {
    XMLName xml.Name
    Text string `xml:",innerxml"`
    Date string `xml:"date,attr"`
}

type statusMarshaller status

func main() {

    var projectStatus statusDB

    err := xml.Unmarshal([]byte(xmlFile), &projectStatus)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("In Go: \"" + projectStatus.Status[0].Text + "\"")
    fmt.Println("In Go: \"" + projectStatus.Status[1].Text + "\"")
    x, err := xml.MarshalIndent(projectStatus, "", "  ")
    if err != nil {
        fmt.Println(err)
        return
    }
    //why this is not printing properly
    fmt.Printf("%s\n", x)
}

func (tagElement *status) UnmarshalXML(d *xml.Decoder, se xml.StartElement) error {
    temp := statusMarshaller{}
    d.DecodeElement(&temp, &se)
    temp.Text = strings.TrimSpace(temp.Text)
    temp.Text = strings.TrimPrefix(temp.Text, "<![CDATA[")
    temp.Text = strings.TrimSuffix(temp.Text, "]]>")
    *tagElement = status(temp)
    return nil
}

func (tagElement status) MarshalXML(d *xml.Encoder, se xml.StartElement) error {
    tagElement.Text = "<![CDATA[" + tagElement.Text + "]]>"
    temp := statusMarshaller(tagElement)
    return d.EncodeElement(temp, se)
}

Go相关问答推荐

如何创建两个连接的io.ReadWriteClosers以用于测试目的

Go GORM创建表,但不创建列

如何将文件从AWS S3存储桶复制到Azure BLOB存储

如果values.yaml文件中不存在某个属性,如何返回默认的FALSE?

我可以在Golang中的另一个类型参数的基础上约束一个类型的参数吗?

如何使用 go 读取 RDF xml 文件中的 XML 命名空间属性

我怎样才能改进这个嵌套逻辑以使其正常工作并提高性能

未实现的 desc = 未知服务 pb.AuthService 我的简单身份验证服务器上出现错误

使用 goroutine 比较 Golang 中的两棵树是等价的

这是实现超时的常见方法,为什么 time.After 不起作用

当填充通道的函数调用未嵌入 goroutine 时,为什么我会遇到死锁?

如何在 gocql 中设置最大池大小?

如果值为 false,gRPC 不返回布尔值

Gorm 预加载给出了模糊的列错误

不能在 *gorm.db 而不是 gorm.db 上使用 WithContext(ctx) 方法

有没有办法判断值是否满足接口中定义的类型约束?

如何使路径/不匹配 Golang net/http 中所有其他不匹配的路径

如何获得Ent中数字列的总和

Golang LinkedList 删除第一个元素

并发 map map导致的 Golang 数据竞争