https://github.com/ttys3/go-xml
fork of golang std xml package which add marshal self-closing tag support
https://github.com/ttys3/go-xml
go-xml-self-closing golang self-closing self-closing-tag xml
Last synced: 12 months ago
JSON representation
fork of golang std xml package which add marshal self-closing tag support
- Host: GitHub
- URL: https://github.com/ttys3/go-xml
- Owner: ttys3
- Created: 2023-06-13T12:21:04.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2023-06-13T14:22:48.000Z (about 3 years ago)
- Last Synced: 2025-01-17T15:42:38.175Z (over 1 year ago)
- Topics: go-xml-self-closing, golang, self-closing, self-closing-tag, xml
- Language: Go
- Homepage:
- Size: 86.9 KB
- Stars: 3
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# go-xml
golang xml package which add marshal self-closing tag support
the code applied from https://go-review.googlesource.com/c/go/+/469495
## Oops
I found this https://twitter.com/ZeCoffee/status/766349635359211520

## usage
Custom MarshalXML ref [https://pkg.go.dev/encoding/xml#Marshal](https://pkg.go.dev/encoding/xml#example-package-CustomMarshalXML)
self-closing tag example:
```go
import "github.com/ttys3/go-xml"
// no `xml` struct tag is needed or can be used here
// since we handle all this in `MarshalXML`
type Foo struct {
Bar string
Comment string
}
// Custom XML marshaler for Foo
func (i Foo) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
attrs := []xml.Attr{
{
Name: xml.Name{Local: "bar"},
Value: i.Bar,
},
{
Name: xml.Name{Local: "comment"},
Value: i.Comment,
},
}
// Create a self-closing tag for Item
empty := xml.EmptyElement{
Name: xml.Name{
Space: "",
Local: "foo",
},
Attr: attrs,
}
// can not use Encode or EncodeElement here, because they will not emit self-closing tag
err := e.EncodeToken(empty)
if err != nil {
return err
}
// Flush must be called since we are not using Encode or EncodeElement
if err := e.Flush(); err != nil {
return err
}
return nil
}
func TestSelfClodingTagFoo(t *testing.T) {
expectedXML := ``
foo := Foo{
Bar: "hello",
Comment: "world",
}
marshaledXML, err := xml.MarshalIndent(foo, "", " ")
if err != nil {
t.Fatalf("Failed to marshal XML: %v", err)
}
if string(marshaledXML) != expectedXML {
t.Errorf("Expected marshaled XML:\n%s\n\nGot:\n%s", expectedXML, marshaledXML)
}
}
```
## related issues
see https://github.com/golang/go/issues/21399
https://go-review.googlesource.com/c/go/+/469495
https://go-review.googlesource.com/c/go/+/59830
https://github.com/nemith/netconf/pull/27/files