From cefb79fa4f5d4d59453d1b09d4864a943214e66e Mon Sep 17 00:00:00 2001 From: Patrick Gundlach Date: Sun, 17 Nov 2024 18:14:58 +0100 Subject: [PATCH] Allow setting of attributes Also document how to create an XML file without reading from storage. --- Readme.md | 41 ++++++++++++++++++++++++++++++++++++++++- xmldecoder.go | 13 +++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 65a2bf8..b71a14e 100644 --- a/Readme.md +++ b/Readme.md @@ -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 @@ -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 &'"}) + 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 + + + + +``` License: BSD-3-Clause License \ No newline at end of file diff --git a/xmldecoder.go b/xmldecoder.go index 14c96de..1e6ef11 100644 --- a/xmldecoder.go +++ b/xmldecoder.go @@ -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