(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,
 1. there are issues with the marshaller
 2. i don't know how to solve them]]></statusMarshaller></status> </statusDB> Program exited.
结论:有人可以解释一下为什么 xml 包会这样做,以及潜在的解决方法是什么?
谢谢!
解决方法
当然,如果包中的 cdata 允许混合元素,那就太好了,但现在我已经找到了解决方法,即上面的代码,进行了一些小更改,以便不在 marhshalXML 中的 statusMarshaller 类型上调用“marshal”功能。相反,我只将 tagElement 转换为 statusMarshaller 类型,然后对该元素进行编码。请参阅以下详细信息:
修订历史记录:
- 修改了 marshalXML 函数中的第二行以删除对 xml.marshal 的调用
- 修改了状态结构以包含 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











이 기사에서는 GO의 패키지 가져 오기 메커니즘을 설명합니다. 명명 된 수입 (예 : 가져 오기 & quot; fmt & quot;) 및 빈 가져 오기 (예 : import _ & quot; fmt & quot;). 명명 된 가져 오기는 패키지 내용을 액세스 할 수있게하고 빈 수입은 t 만 실행합니다.

이 기사에서는 MySQL 쿼리 결과를 GO 구조 슬라이스로 효율적으로 변환합니다. 수동 구문 분석을 피하고 최적의 성능을 위해 데이터베이스/SQL의 스캔 방법을 사용하는 것을 강조합니다. DB 태그 및 Robus를 사용한 구조물 필드 매핑에 대한 모범 사례

이 기사에서는 웹 애플리케이션에서 페이지 간 데이터 전송에 대한 Beego의 NewFlash () 기능을 설명합니다. NewFlash ()를 사용하여 컨트롤러간에 임시 메시지 (성공, 오류, 경고)를 표시하여 세션 메커니즘을 활용하는 데 중점을 둡니다. 한계

이 기사는 단위 테스트를 위해 이동 중에 모의와 스터브를 만드는 것을 보여줍니다. 인터페이스 사용을 강조하고 모의 구현의 예를 제공하며 모의 집중 유지 및 어설 션 라이브러리 사용과 같은 모범 사례에 대해 설명합니다. 기사

이 기사에서는 GO의 제네릭에 대한 사용자 정의 유형 제약 조건을 살펴 봅니다. 인터페이스가 일반 함수에 대한 최소 유형 요구 사항을 정의하여 유형 안전 및 코드 재사성을 향상시키는 방법에 대해 자세히 설명합니다. 이 기사는 또한 한계와 모범 사례에 대해 설명합니다

이 기사는 OS.WriteFile (작은 파일에 적합)과 OS.OpenFile 및 Buffered Writes (큰 파일에 최적)를 비교하여 효율적인 파일 쓰기를 자세히 설명합니다. 강력한 오류 처리, 연기 사용 및 특정 오류 확인을 강조합니다.

이 기사는 GO에서 단위 테스트 작성, 모범 사례, 조롱 기술 및 효율적인 테스트 관리를위한 도구를 다루는 것에 대해 논의합니다.

이 기사는 추적 도구를 사용하여 GO 응용 프로그램 실행 흐름을 분석합니다. 수동 및 자동 계측 기술, Jaeger, Zipkin 및 OpenTelemetry와 같은 도구 비교 및 효과적인 데이터 시각화를 강조합니다.
