element.go

 1// Copyright 2009 The Go Authors. All rights reserved.
 2// Use of this source code is governed by a BSD-style
 3// license that can be found in the LICENSE file.
 4
 5// Copied and modified from Go 1.14 stdlib's encoding/xml
 6
 7package xml
 8
 9// A Name represents an XML name (Local) annotated
10// with a name space identifier (Space).
11// In tokens returned by Decoder.Token, the Space identifier
12// is given as a canonical URL, not the short prefix used
13// in the document being parsed.
14type Name struct {
15	Space, Local string
16}
17
18// An Attr represents an attribute in an XML element (Name=Value).
19type Attr struct {
20	Name  Name
21	Value string
22}
23
24/*
25NewAttribute returns a pointer to an attribute.
26It takes in a local name aka attribute name, and value
27representing the attribute value.
28*/
29func NewAttribute(local, value string) Attr {
30	return Attr{
31		Name: Name{
32			Local: local,
33		},
34		Value: value,
35	}
36}
37
38/*
39NewNamespaceAttribute returns a pointer to an attribute.
40It takes in a local name aka attribute name, and value
41representing the attribute value.
42
43NewNamespaceAttribute appends `xmlns:` in front of namespace
44prefix.
45
46For creating a name space attribute representing
47`xmlns:prefix="http://example.com`, the breakdown would be:
48local = "prefix"
49value = "http://example.com"
50*/
51func NewNamespaceAttribute(local, value string) Attr {
52	attr := NewAttribute(local, value)
53
54	// default name space identifier
55	attr.Name.Space = "xmlns"
56	return attr
57}
58
59// A StartElement represents an XML start element.
60type StartElement struct {
61	Name Name
62	Attr []Attr
63}
64
65// Copy creates a new copy of StartElement.
66func (e StartElement) Copy() StartElement {
67	attrs := make([]Attr, len(e.Attr))
68	copy(attrs, e.Attr)
69	e.Attr = attrs
70	return e
71}
72
73// End returns the corresponding XML end element.
74func (e StartElement) End() EndElement {
75	return EndElement{e.Name}
76}
77
78// returns true if start element local name is empty
79func (e StartElement) isZero() bool {
80	return len(e.Name.Local) == 0
81}
82
83// An EndElement represents an XML end element.
84type EndElement struct {
85	Name Name
86}
87
88// returns true if end element local name is empty
89func (e EndElement) isZero() bool {
90	return len(e.Name.Local) == 0
91}