golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.91k stars 17.65k forks source link

encoding/xml: no way to output cdata field into a nested node #16198

Open akrylysov opened 8 years ago

akrylysov commented 8 years ago

What version of Go are you using (go version)?

go version go1.6.2 darwin/amd64

What operating system and processor architecture are you using (go env)?

GOARCH="amd64"
GOBIN=""
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/akrylysov/go"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.6.2/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.6.2/libexec/pkg/tool/darwin_amd64"
GO15VENDOREXPERIMENT="1"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"

What did you do?

type Test struct {
    Name string `xml:"Person>Name,cdata"`
}

https://play.golang.org/p/aVay4sw8xA

What did you expect to see?

<Test><Person><Name><![CDATA[foo]]</Name></Person></Test>

What did you see instead?

error: xml: invalid tag in field Name of type main.Test: "Person>Name,cdata"

I'm working on a web service which supports JSON and XML as output formats:

type Response struct {
    XMLName xml.Name `json:"-" xml:"response"`
    Foo string       `json:"foo" xml:"foo"`
    Bar string       `json:"bar" xml:"bar"`
}

It worked perfectly, but recently we got a new requirement from our external partner to wrap all XML values into CDATA. So instead of:

<response><foo>foo1</foo><bar>bar2</bar></response>

I need this:

<response><foo><![CDATA[foo1]]</foo><bar><![CDATA[bar2]]</bar></response>

Currently Go doesn't provide a way to do that without introducing a new nested structure like:

type CdataString struct {
    Value string `xml:",cdata"`
}

type Response struct {
    XMLName xml.Name `json:"-" xml:"response"`
    Foo CdataString  `json:"foo" xml:"foo"`
    Bar CdataString  `json:"bar" xml:"bar"`
}

which breaks JSON serialization.

gopherbot commented 6 years ago

Change https://golang.org/cl/144518 mentions this issue: encoding/xml: allow cdata/chardata to be named and nested with annotations