GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — encoding/xml: cannot marshal self-closing tag · Issue #21399 · golang/go

encoding/xml: cannot marshal self-closing tag #21399

New issue
Copy link
New issue
Copy link
Open
Open
encoding/xml: cannot marshal self-closing tag#21399
Copy link
Labels
NeedsFixThe path to resolution is known, but the work has not been done.
Milestone
Backlog

Description

@halfcrazy
halfcrazy
opened on Aug 11, 2017
Issue body actions

Please 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

Activity

Next
  1. Manishearth commented on Aug 29, 2017

    @Manishearth
    Manishearth
    on Aug 29, 2017
    Contributor
    More actions

    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
  2. gopherbot commented on Aug 29, 2017

    @gopherbot
    gopherbot
    on Aug 29, 2017
    Contributor
    More actions

    Change https://golang.org/cl/59830 mentions this issue: encoding/xml: add 'allowempty' tag for self-closing XML tags

    Reacted by Antony Ho, Sivert V. Sæther, Andrey Kolkov and Ignat Remizov
  3. ianlancetaylor
    added this to the Go1.10 milestone on Aug 29, 2017
  4. ianlancetaylor commented on Aug 29, 2017

    @ianlancetaylor
    ianlancetaylor
    on Aug 29, 2017
    Contributor
    More actions

    CC @rsc XML suggestion.

  5. SamWhited commented on Aug 29, 2017

    @SamWhited
    SamWhited
    on Aug 29, 2017
    Contributor
    More actions

    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).

  6. Manishearth commented on Aug 29, 2017

    @Manishearth
    Manishearth
    on Aug 29, 2017
    Contributor
    More actions

    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
  7. Manishearth commented on Aug 29, 2017

    @Manishearth
    Manishearth
    on Aug 29, 2017
    Contributor
    More actions

    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.

    Reacted by Antony Ho
  8. SamWhited commented on Oct 2, 2017

    @SamWhited
    SamWhited
    on Oct 2, 2017
    Contributor
    More actions

    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?

  9. Manishearth commented on Oct 2, 2017

    @Manishearth
    Manishearth
    on Oct 2, 2017
    Contributor
    More actions

    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
  10. SamWhited commented on Oct 2, 2017

    @SamWhited
    SamWhited
    on Oct 2, 2017
    Contributor
    More actions

    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
  11. Manishearth commented on Oct 2, 2017

    @Manishearth
    Manishearth
    on Oct 2, 2017
    Contributor
    More actions

    fair. I'll change the patches. Should/can I tag you for review?

  12. SamWhited commented on Oct 2, 2017

    @SamWhited
    SamWhited
    on Oct 2, 2017
    Contributor
    More actions

    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 :) )

  13. dnaeon commented on Nov 18, 2017

    @dnaeon
    dnaeon
    on Nov 18, 2017
    More actions

    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
  14. rsc
    modified the milestones: Go1.10, Go1.11 on Nov 22, 2017
  15. 40 remaining items

  16. Merovius commented on Sep 6, 2022

    @Merovius
    Merovius
    on Sep 6, 2022
    Contributor
    More actions

    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.

  17. Manishearth commented on Sep 6, 2022

    @Manishearth
    Manishearth
    on Sep 6, 2022
    Contributor
    More actions

    To be clear, this token would only be accepted by EncodeToken, not being created by (*Decoder).Token, correct?

    Yeah.

  18. jybp commented on Dec 8, 2022

    @jybp
    jybp
    on Dec 8, 2022
    More actions

    I'm curious what "clean" solution / workaround people have come up with to write self-closing elements with encoding/xml in the meantime?
    I've only found the following which is just a regex on the whole content:
    https://groups.google.com/g/golang-nuts/c/guG6iOCRu08/m/uMFigsrpCwAJ

  19. hellt commented on Dec 8, 2022

    @hellt
    hellt
    on Dec 8, 2022
    More actions

    @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
  20. nemith commented on Feb 17, 2023

    @nemith
    nemith
    on Feb 17, 2023
    Contributor
    More actions

    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

  21. gopherbot commented on Feb 18, 2023

    @gopherbot
    gopherbot
    on Feb 18, 2023
    Contributor
    More actions

    Change https://go.dev/cl/469495 mentions this issue: encoding/xml: Add EmptyElement token.

    Reacted by Peter Kristensen, Vitor Hugo, Armando de la Vega, Dmitry Galinsky and Ignat Remizov
  22. StEvUgnIn commented on Apr 22, 2023

    @StEvUgnIn
    StEvUgnIn
    on Apr 22, 2023
    More actions

    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
  23. nemith commented on Apr 27, 2023

    @nemith
    nemith
    on Apr 27, 2023
    Contributor
    More actions

    @StEvUgnIn Pretty much eliminates stream mode and has overhead with regexp matching.

  24. Merovius commented on Apr 27, 2023

    @Merovius
    Merovius
    on Apr 27, 2023
    Contributor
    More actions

    It's also not correct - it would, for example, also apply the replacement in comments.

    Reacted by Brandon Bennett, Alan Donovan and Ignat Remizov
  25. ttys3 commented on Jun 13, 2023

    @ttys3
    ttys3
    on Jun 13, 2023
    More actions

    just created a mod with patch in https://go.dev/cl/469495 applied.

    and fixed a indent issue. in case someone need a workaround, here is the repo:

    https://github.com/ttys3/go-xml#usage

    Reacted by Armando de la Vega, JBP, Brandon Bennett, barkyq and Ignat Remizov
  26. chadlwm commented on Sep 13, 2023

    @chadlwm
    chadlwm
    on Sep 13, 2023
    More actions

    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

  27. chadlwm commented on Sep 13, 2023

    @chadlwm
    chadlwm
    on Sep 13, 2023
    More actions

    the repo seems fine: https://github.com/ECUST-XX/xml/tree/master
    however, why the offical doesnot support this feature? what's the key point?

  28. barkyq commented on Apr 4, 2024

    @barkyq
    barkyq
    on Apr 4, 2024
    More actions

    just created a mod with patch in https://go.dev/cl/469495 applied.

    and fixed a indent issue. in case someone need a workaround, here is the repo:

    https://github.com/ttys3/go-xml#usage

    @ttys3 thanks!

  29. ianlancetaylor commented on Sep 4, 2024

    @ianlancetaylor
    ianlancetaylor
    on Sep 4, 2024
    Contributor
    More actions

    See #69273 for a concrete proposal.

  30. ignatremizov commented on Jun 11, 2025

    @ignatremizov
    ignatremizov
    on Jun 11, 2025
    More actions

    Ran into this issue, would love to see an implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsFixThe path to resolution is known, but the work has not been done.

    Type

    No type

    Projects

    No projects

      Milestone

      • BacklogNo due date

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402792 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.