目錄
问题内容
解决方法
首頁 後端開發 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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

從前端轉型後端開發,學習Java還是Golang更有前景? 從前端轉型後端開發,學習Java還是Golang更有前景? Apr 02, 2025 am 09:12 AM

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

Beego ORM中如何指定模型關聯的數據庫? Beego ORM中如何指定模型關聯的數據庫? Apr 02, 2025 pm 03:54 PM

在BeegoORM框架下,如何指定模型關聯的數據庫?許多Beego項目需要同時操作多個數據庫。當使用Beego...

Go的爬蟲Colly中Queue線程的問題是什麼? Go的爬蟲Colly中Queue線程的問題是什麼? Apr 02, 2025 pm 02:09 PM

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

Go語言中用於浮點數運算的庫有哪些? Go語言中用於浮點數運算的庫有哪些? Apr 02, 2025 pm 02:06 PM

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

在Go語言中使用Redis Stream實現消息隊列時,如何解決user_id類型轉換問題? 在Go語言中使用Redis Stream實現消息隊列時,如何解決user_id類型轉換問題? Apr 02, 2025 pm 04:54 PM

Go語言中使用RedisStream實現消息隊列時類型轉換問題在使用Go語言與Redis...

GoLand中自定義結構體標籤不顯示怎麼辦? GoLand中自定義結構體標籤不顯示怎麼辦? Apr 02, 2025 pm 05:09 PM

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...

在 Go 語言中,為什麼使用 Println 和 string() 函數打印字符串會出現不同的效果? 在 Go 語言中,為什麼使用 Println 和 string() 函數打印字符串會出現不同的效果? Apr 02, 2025 pm 02:03 PM

Go語言中字符串打印的區別:使用Println與string()函數的效果差異在Go...

See all articles