xmlbuilder

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2022 License: Apache-2.0, MIT Imports: 3 Imported by: 0

README

XML builder for Golang

xml-builder is a metaprogramming approach to build XML document like lxml in Python.

Creating a XML document

The following example creates an XML document from scratch using the xml-builder package and outputs its indented contents to stdout.

e := Tags(struct{ person, gender, firstname, lastname Tag }{})
doc := Doc(e.person(
	e.gender("female"),
	e.firstname("Anna"),
	e.lastname("Smith"),
))
bytes, _ := xml.MarshalIndent(doc, "", "    ")
fmt.Println(string(bytes))

Will output:

<person>
  <gender>female</gender>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

Attributes

This example illustrates how to define attributes in element

e := Tags(struct{ person, gender Tag }{})
doc := Doc(e.person(
	e.gender("female", Attrs{"a": "b", "xmlns:c": "xml.builder"}),
))
bytes, _ := xml.MarshalIndent(doc, "", "    ")
fmt.Println(string(bytes))

Will output:

<person>
  <gender a="b" xmlns:c="xml.builder">female</gender>
</person>

InstantElement

When unable to define tags, you can create as instant element as following:

person := E("person")
gender := E("gender", "female")
person.Append(gender)

Hook

When element name is snakecase or kebabcase, assuming you already had a function named snakecase, you can add a hook when creating tags as following:

e := Tags(struct{ firstName, lastName Tag }{}, func(name *xml.Name) {
	name.Local = snakecase(name.Local)
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Tags

func Tags[T any](tags T, hooks ...func(*xml.Name)) T

Types

type Attrs

type Attrs map[string]string

type Document

type Document struct {
	// contains filtered or unexported fields
}

Simply a wrapper since Element has no pointer receiver to MarshalXML method

func Doc

func Doc(element Element) Document

type Element

type Element struct {
	// contains filtered or unexported fields
}

func E

func E(name string, tokens ...xml.Token) Element

func (*Element) Append

func (e *Element) Append(value Element) *Element

func (Element) MarshalXML

func (e Element) MarshalXML(encoder *xml.Encoder, _start xml.StartElement) error

type Tag

type Tag func(tokens ...xml.Token) Element

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL