GeezerVison is showing github.com — encoding/xml: cannot marshal self-closing tag · Issue #21399 · golang/go
encoding/xml: cannot marshal self-closing tag #21399Labels NeedsFixThe path to resolution is known, but the work has not been done. DescriptionPlease answer these questions before submitting your issue. Thanks!
What version of Go are you using (go version)?
go version go1.8.3 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/xxx/.go:/Users/xxx/workspace/goproject"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.8.3/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.8.3/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/53/r61bh2fj1hg9n0w03fs__7kc0000gn/T/go-build440341166=/tmp/go-build -gno-record-gcc-switches -fno-common"
CXX="clang++"
CGO_ENABLED="1"
PKG_CONFIG="pkg-config"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
What did you do?
I want to marshal a xml struct which has a self-closing tag field. After looking up in golang doc, there isn't an official support. In google group they use string.Replace, it's ugly. It seems we could write marshal func for the custom struct, by i'm willing to see an official support like
type Person struct {
XMLName xml.Name `xml:"person"`
Id int `xml:"id,attr"`
FirstName string `xml:"name>first"`
LastName string `xml:"name>last"`
Age int `xml:"age"`
Height float32 `xml:"height,omitempty"`
Married bool
Address
Comment string `xml:",comment"`
Balabala string `xml:"balabala,allowempty"` // i want something like this
}
In xml standard, a self-closing tag is permitted.
https://www.w3.org/TR/REC-xml/#dt-empty
And empty-element tag should be used, and should only be used, for elements which are declared EMPTY.
https://www.w3.org/TR/REC-xml/#d0e2480 Reacted by Rafael, cachekeyval, João Pereira, Dieter Pisarewski, Ibraim Medina, und3fined, Behrang Saeedzadeh, Lomanic, patpir, Runtime Terror and 45 more Reacted by Bård Aase, Claus F. Strasburger, João Pereira, thaspius, Prashanth Bhat, taktv6, Alexis Jeandeau, Vitor Hugo, Andrew Nee, cylldby and 1 more Reacted by Alex Salt, Vitor Hugo and Andrew Nee ActivityManishearth commented on Aug 29, 2017 I like this idea; though i suspect the community will have to agree on it (and also the naming of the tag)
However, I whipped up a quick implementation at https://go-review.googlesource.com/59830 .
I'll polish it up and add tests if this proposal actually goes through. Reacted by halfcrazy, Antony Ho, Sivert V. Sæther and Ignat Remizov gopherbot commented on Aug 29, 2017 Reacted by Antony Ho, Sivert V. Sæther, Andrey Kolkov and Ignat Remizov ianlancetaylor commented on Aug 29, 2017 SamWhited commented on Aug 29, 2017
Change https://golang.org/cl/59830 mentions this issue: encoding/xml: add 'allowempty' tag for self-closing XML tags
The proposed patch only works for marshaling structs. What if we're using the EncodeToken method and write a StartElement immediately followed by its corresponding EndElement? If this ends up being desired and it were an option on the Encoder instead it would work in both places (although it would be global for all tags, not local to specific struct fields, but that seems more desriable to me). Manishearth commented on Aug 29, 2017 We still need the ability to output non-selfclosing pairs of tags. The idea is to give the user the option to make certain fields self closing, not to do that for all fields. Reacted by halfcrazy, Alexey Ankip, thaspius, Jean-Sébastien Goupil and Ignat Remizov Manishearth commented on Aug 29, 2017 Oh, I see, you're suggesting this be global. Hm. I don't really like the idea of making this a global change, but we could also make it an option on the marshaler. SamWhited commented on Oct 2, 2017
I don't really like the idea of making this a global change
Is there a benefit to only doing this for some elements and not for others? Manishearth commented on Oct 2, 2017 For the same reason this bug exists in the first place; not all XML parsers handle this correctly and I wanted maximum flexibility.
I'm fine with doing it the other way though. Reacted by thaspius, Evgenii Omelchenko, yokhahn and Ignat Remizov SamWhited commented on Oct 2, 2017
not all XML parsers handle this correctly and I wanted maximum flexibility
If a parser did not handle this you couldn't mix the two anyways, you'd just have to turn it on or off entirely to make sure that parser would work.
In case there's confusion, I'm not suggesting that we always do self-closing tags or non-self-closing tags, but that an individual *Encoder should be configurable to do one or the other. Reacted by Brandon Bennett Manishearth commented on Oct 2, 2017 fair. I'll change the patches. Should/can I tag you for review? SamWhited commented on Oct 2, 2017
fair. I'll change the patches. Should/can I tag you for review?
I don't have +2 permissions, but I'm happy to run trybots and provide feedback (also, setting this on the Encoder is my suggestion, but I don't actually have any authority here, so grain of salt until rsc or someone replies :) ) dnaeon commented on Nov 18, 2017 Can we expect this to be implemented in Go 1.10?
Currently we have a Go library, that needs to communicate with a remote API endpoint, which can only understand empty XML elements with self-closing tags.
With the current implementation of XML package we are not able to use Go in order to communicate with that API endpoint. I realize that this is an issue of the remote side by not supporting both ways of specifying empty elements, but having the option to define how empty elements are defined in Go structs would be very useful and would allow us to overcome such edge cases.
Thanks,
Marin Reacted by Ignat Remizov and Rick Beton Reacted by Brandon Bennett Merovius commented on Sep 6, 2022 I'm just running into this problem myself. I'd be interested in a fix too.
Side-note: This should probably be NeedsInvestigation or NeedsDecision, not NeedsFix.
@Manishearth
A potential middle ground is to make the field only affect marshalling structs, and for EncodeToken add a new SelfClosing token variant so the caller can deal with it.
To be clear, this token would only be accepted by EncodeToken, not being created by (*Decoder).Token, correct? Because otherwise, this would probably break consumers using that API, who type-switch over the returned tokens. Though we could add an option to *Decoder to generate them.
An alternative might be to add an Attr []Attr field to EndElement, as that's what a self-closing tag syntactically is. The restriction would be the same, that the *Decoder continues to synthesize StartElement/EndElement pairs, but EncodeToken could accept them. This seems nicer than adding a new token type, but it's probably less compatible.
Personally, I consider it more important to support the low-level (i.e. EncodeToken) use-case, than support he high-level (i.e. EncodeElement) use-case. It is always possible to drop to a lower level, but not vice-versa. I'm not opposed to solve it for EncodeElement as well, though. Manishearth commented on Sep 6, 2022
To be clear, this token would only be accepted by EncodeToken, not being created by (*Decoder).Token, correct?
Yeah. jybp commented on Dec 8, 2022 hellt commented on Dec 8, 2022 @jybp we use this
func forceSelfClosingTags(b []byte) []byte {
emptyTagIdxs := regexp.MustCompile(`<(\w+)></\w+>`).FindAllSubmatchIndex(b, -1)
var nb []byte
for _, idx := range emptyTagIdxs {
// get everything in b up till the first of the submatch indexes (this is the start of an
// "empty" <thing></thing> tag), then get the name of the tag and put it in a self-closing
// tag.
nb = append(b[0:idx[0]], fmt.Sprintf("<%s/>", b[idx[2]:idx[3]])...) //nolint: gocritic
// finally, append everything *after* the submatch indexes
nb = append(nb, b[len(b)-(len(b)-idx[1]):]...)
}
return nb
}Reacted by Brandon Bennett, HoangNguyen689, p3pega, Nico Braun and Ignat Remizov nemith commented on Feb 17, 2023 I have been looking for this since I started writing Go and my original issue #6896 and still running into this.
In my particular use case a self-closing is being used (probably improperly by the API) to be a bool. If it exists then we get a "true" if it's missing we get a "false". There is a second use case where self-closed tags are used as variables, but there are ok workarounds for that.
It seems a custom type would be needed to follow the proposals "allowempty" proposal to be used a extant bool, but there are at least workarounds.
Given a "RawXML" token type we could have a proper workaround. #26756 gopherbot commented on Feb 18, 2023 Reacted by Peter Kristensen, Vitor Hugo, Armando de la Vega, Dmitry Galinsky and Ignat Remizov StEvUgnIn commented on Apr 22, 2023 Do this
import (
"regexp"
)
func SelfClosing(xml []byte) ([]byte, error) {
regex, err := regexp.Compile(`></[A-Za-z0-9_]+>`)
return regex.ReplaceAll(xml, []byte("/>")), err
}Reacted by Axel Wagner, Brandon Bennett, Brent S., Peter Kristensen, Armando de la Vega, Alan Donovan, HoangNguyen689, fiurþorn, p3pega, DBX12 and 3 more nemith commented on Apr 27, 2023 @StEvUgnIn Pretty much eliminates stream mode and has overhead with regexp matching. Merovius commented on Apr 27, 2023 It's also not correct - it would, for example, also apply the replacement in comments. Reacted by Brandon Bennett, Alan Donovan and Ignat Remizov ttys3 commented on Jun 13, 2023 Reacted by Armando de la Vega, JBP, Brandon Bennett, barkyq and Ignat Remizov chadlwm commented on Sep 13, 2023
Do this
import (
"regexp"
)
func SelfClosing(xml []byte) ([]byte, error) {
regex, err := regexp.Compile(`></[A-Za-z0-9_]+>`)
return regex.ReplaceAll(xml, []byte("/>")), err
}
the following case not work:
<student><name>xxx</name></student>
the ></student> also match the regex rule, but it's wrong chadlwm commented on Sep 13, 2023 barkyq commented on Apr 4, 2024 ianlancetaylor commented on Sep 4, 2024 See #69273 for a concrete proposal. ignatremizov commented on Jun 11, 2025 Ran into this issue, would love to see an implementation
MetadataMetadataNeedsFixThe path to resolution is known, but the work has not been done. DevelopmentNo branches or pull requestsIssue actions
|