目录
问题内容
解决方法
首页 后端开发 Golang 为什么 (encoder).EncodeElement 忽略',innerxml”标签?

为什么 (encoder).EncodeElement 忽略',innerxml”标签?

Feb 09, 2024 am 08:03 AM

为什么 (encoder).EncodeElement 忽略“,innerxml”标签?

php小编小新在这里为大家解答一个常见问题:“为什么 (encoder).EncodeElement 忽略“,innerxml”标签?”。这个问题涉及到在使用 (encoder).EncodeElement 方法时,为什么会出现无法编码 innerxml 标签的情况。下面我们将详细回答这个问题,帮助读者更好地理解和解决相关问题。

问题内容

用途:我有一个 xml 文档,其中包含许多混合内容 cdata 元素,我需要以编程方式编辑这些元素。令人烦恼的是,由于 cdata 元素具有其他/混合内容,默认的“,cdata”标记无法正常工作(根据 xml 规范)。如果您对此具体细节有疑问,请告诉我。

问题:在下面的简化示例中,我将其中包含 cdata 的元素标记为“,innerxml”,以便自己处理前缀/后缀。通过解组,一切都按预期工作,但是通过编组(编码),特殊字符被转义。当标签明确表示不转义时(通过“,innerxml”标签),为什么 EncodeElement 方法会转义特殊字符?当我在文档中读到此方法时,它让我参考 xml.Marshal 方法,其中包含以下内容:

<code>
a field with tag ",innerxml" is written verbatim, not subject to the usual marshaling procedure.
</code>
登录后复制

示例:

以下是代码(也可在 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.
登录后复制

结论:有人可以解释一下为什么 xml 包会这样做,以及潜在的解决方法是什么?

谢谢!

解决方法

当然,如果包中的 cdata 允许混合元素,那就太好了,但现在我已经找到了解决方法,即上面的代码,进行了一些小更改,以便不在 marhshalXML 中的 statusMarshaller 类型上调用“marshal”功能。相反,我只将 tagElement 转换为 statusMarshaller 类型,然后对该元素进行编码。请参阅以下详细信息:

修订历史记录:

  1. 修改了 marshalXML 函数中的第二行以删除对 xml.marshal 的调用
  2. 修改了状态结构以包含 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)
}
登录后复制

以上是为什么 (encoder).EncodeElement 忽略',innerxml”标签?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Go语言包导入:带下划线和不带下划线的区别是什么? Go语言包导入:带下划线和不带下划线的区别是什么? Mar 03, 2025 pm 05:17 PM

本文解释了GO的软件包导入机制:命名imports(例如导入“ fmt”)和空白导入(例如导入_ fmt; fmt;)。 命名导入使包装内容可访问,而空白导入仅执行t

Beego框架中NewFlash()函数如何实现页面间短暂信息传递? Beego框架中NewFlash()函数如何实现页面间短暂信息传递? Mar 03, 2025 pm 05:22 PM

本文解释了Beego的NewFlash()函数,用于Web应用程序中的页间数据传输。 它专注于使用newflash()在控制器之间显示临时消息(成功,错误,警告),并利用会话机制。 Lima

Go语言中如何将MySQL查询结果List转换为自定义结构体切片? Go语言中如何将MySQL查询结果List转换为自定义结构体切片? Mar 03, 2025 pm 05:18 PM

本文详细介绍了MySQL查询结果的有效转换为GO结构切片。 它强调使用数据库/SQL的扫描方法来最佳性能,避免手动解析。 使用DB标签和Robus的结构现场映射的最佳实践

如何编写模拟对象和存根以进行测试? 如何编写模拟对象和存根以进行测试? Mar 10, 2025 pm 05:38 PM

本文演示了创建模拟和存根进行单元测试。 它强调使用接口,提供模拟实现的示例,并讨论最佳实践,例如保持模拟集中并使用断言库。 文章

如何定义GO中仿制药的自定义类型约束? 如何定义GO中仿制药的自定义类型约束? Mar 10, 2025 pm 03:20 PM

本文探讨了GO的仿制药自定义类型约束。 它详细介绍了界面如何定义通用功能的最低类型要求,从而改善了类型的安全性和代码可重复使用性。 本文还讨论了局限性和最佳实践

Go语言如何便捷地写入文件? Go语言如何便捷地写入文件? Mar 03, 2025 pm 05:15 PM

本文详细介绍了在GO中详细介绍有效的文件,将OS.WriteFile(适用于小文件)与OS.openfile和缓冲写入(最佳大型文件)进行比较。 它强调了使用延迟并检查特定错误的可靠错误处理。

您如何在GO中编写单元测试? 您如何在GO中编写单元测试? Mar 21, 2025 pm 06:34 PM

本文讨论了GO中的编写单元测试,涵盖了最佳实践,模拟技术和有效测试管理的工具。

如何使用跟踪工具了解GO应用程序的执行流? 如何使用跟踪工具了解GO应用程序的执行流? Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探讨了GO应用程序执行流。 它讨论了手册和自动仪器技术,比较诸如Jaeger,Zipkin和Opentelemetry之类的工具,并突出显示有效的数据可视化

See all articles