Skip to content

Commit

Permalink
Allow setting of attributes
Browse files Browse the repository at this point in the history
Also document how to create an XML file without reading from storage.
  • Loading branch information
pgundlach committed Nov 17, 2024
1 parent d4a5063 commit cefb79f
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
41 changes: 40 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

Go XML is a DOM based XML representation for Go. The entire XML
file is read into a set of structs and can be accessed without keeping the
source file open.
source file open. You can also use this library to construct and serialize an XML file.

Used in https://github.com/speedata/goxpath

Expand Down Expand Up @@ -57,6 +57,45 @@ func main() {
}
```

Constructing an XML file:

~~~go
package main

import (
"encoding/xml"
"fmt"

"github.com/speedata/goxml"
)

func main() {
d := goxml.XMLDocument{}
root := &goxml.Element{Name: "root"}
d.Append(root)
cd := goxml.CharData{Contents: "\n "}
root.Append(cd)
elt1 := &goxml.Element{Name: "element"}
elt1.SetAttribute(xml.Attr{Name: xml.Name{Local: "attr"}, Value: "element 1"})
elt1.SetAttribute(xml.Attr{Name: xml.Name{Local: "attr2"}, Value: "some <value> &'"})
root.Append(elt1)
root.Append(cd)
elt2 := &goxml.Element{Name: "element"}
elt2.SetAttribute(xml.Attr{Name: xml.Name{Local: "attr"}, Value: "element 2"})
root.Append(elt2)
root.Append(goxml.CharData{Contents: "\n"})
fmt.Println(d.ToXML())
}
~~~

prints

```xml
<root>
<element attr="element 1" attr2="some &lt;value> &amp;'" />
<element attr="element 2" />
</root>
```


License: BSD-3-Clause License
13 changes: 13 additions & 0 deletions xmldecoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,19 @@ func (elt Element) Children() []XMLNode {
return elt.children
}

// SetAttribute appends attr to the list of attributes of elt. If an attribute
// of this name already exists, the existing one will be discarded.
func (elt *Element) SetAttribute(attr xml.Attr) {
var newAttributes = make([]xml.Attr, 0, len(elt.attributes)+1)
for _, curattr := range elt.attributes {
if curattr.Name != attr.Name {
newAttributes = append(newAttributes, curattr)
}
}
newAttributes = append(newAttributes, attr)
elt.attributes = newAttributes
}

// Attributes returns all attributes for this element
func (elt Element) Attributes() []*Attribute {
var attribs []*Attribute
Expand Down

0 comments on commit cefb79f

Please sign in to comment.