搜尋
首頁後端開發Golang為什麼 (encoder).EncodeElement 忽略「,innerxml」標籤?

为什么 (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><statusMarshaller date="today"><![CDATA[today is < yesterday]]></statusMarshaller></status>
  <status><statusMarshaller date="yesterday"><![CDATA[PM,&#xA;      1. there are issues with the marshaller&#xA;      2. i don&#39;t know how to solve them]]></statusMarshaller></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中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
了解Goroutines:深入研究GO的並發了解Goroutines:深入研究GO的並發May 01, 2025 am 12:18 AM

goroutinesarefunctionsormethodsthatruncurranceingo,啟用效率和燈威量。 1)shememanagedbodo'sruntimemultimusingmultiplexing,允許千sstorunonfewerosthreads.2)goroutinessimproverentimensImproutinesImproutinesImproveranceThroutinesImproveranceThrountinesimproveranceThroundinesImproveranceThroughEasySytaskParallowalizationAndeff

了解GO中的初始功能:目的和用法了解GO中的初始功能:目的和用法May 01, 2025 am 12:16 AM

purposeoftheInitfunctionoIsistoInitializeVariables,setUpConfigurations,orperformneccesSetarySetupBeforEtheMainFunctionExeCutes.useInitby.UseInitby:1)placingitinyourcodetorunautoamenationally oneraty oneraty oneraty on inity in ofideShortAndAndAndAndForemain,2)keepitiTshortAntAndFocusedonSimImimpletasks,3)

了解GO界面:綜合指南了解GO界面:綜合指南May 01, 2025 am 12:13 AM

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

從恐慌中恢復:何時以及如何使用recover()從恐慌中恢復:何時以及如何使用recover()May 01, 2025 am 12:04 AM

在Go中使用recover()函數可以從panic中恢復。具體方法是:1)在defer函數中使用recover()捕獲panic,避免程序崩潰;2)記錄詳細的錯誤信息以便調試;3)根據具體情況決定是否恢復程序執行;4)謹慎使用,以免影響性能。

您如何使用'字符串”包裝操縱串中的琴弦?您如何使用'字符串”包裝操縱串中的琴弦?Apr 30, 2025 pm 02:34 PM

本文討論了使用GO的“字符串”軟件包進行字符串操作,詳細介紹了共同的功能和最佳實踐,以提高效率並有效地處理Unicode。

您如何使用'加密”在Go中執行加密操作的軟件包?您如何使用'加密”在Go中執行加密操作的軟件包?Apr 30, 2025 pm 02:33 PM

本文使用GO的“加密”軟件包詳細介紹了加密操作,討論了安全實施的關鍵生成,管理和最佳實踐。

您如何使用'時間”處理日期和時間的包裝?您如何使用'時間”處理日期和時間的包裝?Apr 30, 2025 pm 02:32 PM

本文詳細介紹了GO的“時間”包用於處理日期,時間和時區,包括獲得當前時間,創建特定時間,解析字符串以及測量經過的時間。

您如何使用'反映”包裹檢查GO中變量的類型和值?您如何使用'反映”包裹檢查GO中變量的類型和值?Apr 30, 2025 pm 02:29 PM

文章討論了使用GO的“反射”軟件包進行可變檢查和修改,突出顯示方法和性能注意事項。

See all articles

熱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

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

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器