xmldoc

package
v0.0.0-...-7538080 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2025 License: BSD-2-Clause Imports: 7 Imported by: 0

README

XML mini library

import "github.com/OpenPrinting/go-mfp/util/xmldoc"

This package provides mini library for convenient decoding of the XML messages.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func XMLErrMissed

func XMLErrMissed(name string) error

XMLErrMissed creates an error that happens when some required child element is missed

func XMLErrNew

func XMLErrNew(elem Element, text string) error

XMLErrNew is equal to XMLErrWrap(elem,errors.New(text)).

func XMLErrWrap

func XMLErrWrap(elem Element, err error) error

XMLErrWrap "wraps" the error in the context of the Element.

func XMLErrWrapAttr

func XMLErrWrapAttr(attr Attr, err error) error

XMLErrWrapAttr "wraps" the error in the context of the Attr.

func XMLErrWrapName

func XMLErrWrapName(name string, err error) error

XMLErrWrapName "wraps" the error in the context of the Element. or Attr with the specified name

Types

type Attr

type Attr struct {
	Name  string // Attribute name
	Value string // Attribute value
}

Attr represents an XML element attribute

func (Attr) Equal

func (attr Attr) Equal(attr2 Attr) bool

Equal tests that two XML attrubutes are equal.

type Element

type Element struct {
	Name     string    // Name of this element (ns:name)
	Text     string    // Element body
	Attrs    []Attr    // Element attributes
	Children []Element // All children
}

Element represents a single decoded XML Element

func Decode

func Decode(ns Namespace, in io.Reader) (Element, error)

Decode parses XML document, and represents it as a tree of [Element]s.

Namespace prefixes are rewritten according to the 'ns' map. Full namespace URL used as map index, and value that corresponds to the index replaced with map value. If URL is not found in the map, prefix replaced with "-" string

func WithAttrs

func WithAttrs(name string, attrs ...Attr) Element

WithAttrs is the convenience function for constricting XML tree.

It construct Element with attributes.

func WithChildren

func WithChildren(name string, children ...Element) Element

WithChildren is the convenience function for constricting XML tree.

It construct Element with Children.

func WithText

func WithText(name, text string) Element

WithText is the convenience function for constricting XML tree.

It construct Element with Text.

func (Element) AttrByName

func (root Element) AttrByName(name string) (Attr, bool)

AttrByName searches element attributes by name.

It returns (attr, true) if element was found or (Attr{}, false) if not.

func (Element) AttrsMap

func (root Element) AttrsMap() map[string]Attr

AttrsMap returns map of the Element's attributes, indexed by name.

If there are multiple attributes with the same name, only the first is returned.

func (Element) ChildByName

func (root Element) ChildByName(name string) (Element, bool)

ChildByName searches child element by name.

It returns (child, true) if element was found or (Element{}, false) if not.

func (Element) ChildrenMap

func (root Element) ChildrenMap() map[string]Element

ChildrenMap returns map of the Element's children, indexed by name.

If there are multiple children with the same name, only the first is returned.

func (Element) Encode

func (root Element) Encode(w io.Writer, ns Namespace) error

Encode writes XML into io.Writer in the compact form.

xmlns attributes automatically created for all Namespace entries, marked with [Namespace.Used] flag or actually referred by the XML tree.

func (Element) EncodeIndent

func (root Element) EncodeIndent(w io.Writer, ns Namespace,
	indent string) error

EncodeIndent writes XML into io.Writer in the indented form.

See Element.Encode for details.

func (Element) EncodeIndentString

func (root Element) EncodeIndentString(ns Namespace, indent string) string

EncodeIndentString writes XML into io.Writer in the indented form and returns string.

See Element.Encode for details.

func (Element) EncodeString

func (root Element) EncodeString(ns Namespace) string

EncodeString writes XML into io.Writer in the compact form and returns string.

See Element.Encode for details.

func (Element) Equal

func (root Element) Equal(root2 Element) bool

Equal tests that two XML trees are equal.

func (Element) Expand

func (root Element) Expand(mapping func(string) string) Element

Expand replaces ${var} or $var in the XML [Element.Text] and [Attr.Value] of the entire XML tree based on the mapping function and returns rewritten XML tree.

It is uses os.Expand function for strings substitution.

func (Element) IsZero

func (root Element) IsZero() bool

IsZero reports if Element equal to zero element

func (Element) Iterate

func (root Element) Iterate() *Iter

Iterate begins iteration of the XML Element tree.

The newly created iterator points to the dummy pseudo-element. After Iter.Next is called for the very first time, the current node becomes root.

So the valid usage pattern is following

iter := root.Iterate()
for iter.Next() {
  // Do something
}

Important note: the structure of the XML tree MUST NOT be modified during iterations. Otherwise, behavior is undefined.

func (Element) Lookup

func (root Element) Lookup(lookups ...*Lookup) *Lookup

Lookup searches for children elements, multiple elements a time.

Use pattern:

  element1 = Lookup(Name: "Element1"}
  element2 = Lookup(Name: "Element2"}
  element3 = Lookup(Name: "Element3"}

  root.Lookup(&element1,&element2,&element3)
  if element1.Found{
      . . .
  }
  if element2.Found{
      . . .
  }
  if element2.Found{
      . . .
  }

If root contains multiple children with the same name, the first child always returned.

It returns the first not found Lookup element with the [Lookup.Required] flag set, or nil of all required elements are found.

Note, if there are missed required elements, it is not guaranteed that all lookup requests will be processed.

func (Element) LookupAttrs

func (root Element) LookupAttrs(lookups ...*LookupAttr) *LookupAttr

LookupAttrs is like Element.Lookup, but for attributes, not for children elements.

func (Element) Similar

func (root Element) Similar(root2 Element) bool

Similar tests that two XML trees are similar, which means that they are equal, ignoring difference in order of children and attributes with the different names.

Note, children and attributes with the same name still needs to be ordered equally.

type Iter

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

Iter allows iteration of the XML tree as a linear sequence of elements.

Assuming the tree has the following structure:

Root
  |--> Child 1
  |      |--> Child 1.1
  |      `--> Child 1.2
  `--> Child 2
         |--> Child 2.1
         `--> Child 2.2

The nodes will be returned in the following order:

  • Root
  • Child 1
  • Child 1.1
  • Child 1.2
  • Child 2
  • Child 2.1
  • Child 2.2

func (*Iter) Done

func (i *Iter) Done() bool

Done reports if iteration is done.

func (*Iter) Elem

func (i *Iter) Elem() *Element

Elem returns the current element.

func (*Iter) Next

func (i *Iter) Next() bool

Next moves iterator to the next Element in order. It returns false at the end.

func (*Iter) Path

func (i *Iter) Path() string

Path returns a full path from root to the current element. Path starts with the '/' character and uses '/' as a separator.

type Lookup

type Lookup struct {
	Name     string  // Requested element name
	Required bool    // This is required element
	Elem     Element // Returned element data
	Found    bool    // Becomes true, if element was found
}

Lookup contains element name for lookup by name and received lookup result.

It is optimized for looking up multiple elements at once.

See also: Element.Lookup

type LookupAttr

type LookupAttr struct {
	Name     string // Requested element name
	Required bool   // This is required element
	Attr     Attr   // Returned element data
	Found    bool   // Becomes true, if element was found
}

LookupAttr is like Lookup, but for attributes, not for children.

type Namespace

type Namespace []struct {
	URL    string // Namespace URL
	Prefix string // Namespace prefix
	Used   bool   // Flag for [Namespace.MarkUsed] and friends
}

Namespace maps XML namespace URLs to short prefixes.

Namespace initialization may look as follows:

var ns = Namespace{
        {"http://www.w3.org/2003/05/soap-envelope", "s"},
        {"https://www.w3.org/2003/05/soap-envelope", "s"},
        {"http://schemas.xmlsoap.org/ws/2005/04/discovery", "d"},
        {"https://schemas.xmlsoap.org/ws/2005/04/discovery", "d"},
}

When used with the Decode function, this namespace specifies that names all elements and attributes whose prefix in the original document maps to the "http://www.w3.org/2003/05/soap-envelope" URL will be rewritten to use prefix "s" and so on.

When used with the [Encode] function, Namespace will be automatically written to output as a set of root element's xmlns attributes. Moreover, only actually used entries will be written to output.

If Namespace contains multiple entries with the same Prefix and different URLs, all entries will be taken in account by Decode, and Encode will use the first matching entry in the list.

func (*Namespace) Append

func (ns *Namespace) Append(url string, prefix string)

Append appends item to the Namespace

func (Namespace) ByPrefix

func (ns Namespace) ByPrefix(p string) (string, bool)

ByPrefix searches Namespace by name prefix.

It returns (URK, true) if requested element was found, or ("", false) otherwise.

func (Namespace) ByURL

func (ns Namespace) ByURL(u string) (string, bool)

ByURL searches Namespace by namespace URL.

It returns (Prefix, true) if requested element was found, or ("", false) otherwise.

It automatically handles the "http://www.w3.org/XML/1998/namespace" as identifier of the "xml" namespace.

See also Namespace.IndexByURL

func (Namespace) Clone

func (ns Namespace) Clone() Namespace

Clone creates a copy of Namespace.

func (Namespace) ExportUsed

func (ns Namespace) ExportUsed() []Attr

ExportUsed exports marked as used subset of the Namespace as a sequence of xmlns attributes.

func (Namespace) IndexByPrefix

func (ns Namespace) IndexByPrefix(p string) int

IndexByPrefix searches Namespace by name prefix.

It returns index of the found element or -1, if there is no match.

See also: Namespace.ByPrefix

func (Namespace) IndexByURL

func (ns Namespace) IndexByURL(u string) int

IndexByURL searches Namespace by namespace URL.

It returns index of the found element or -1, if there is no match.

See also: Namespace.ByURL

func (Namespace) MarkUsed

func (ns Namespace) MarkUsed(root Element)

MarkUsed marks Namespace entries that actually used by the XML tree by setting [Namespace.Used] flag.

func (Namespace) MarkUsedName

func (ns Namespace) MarkUsedName(name string)

MarkUsedName accepts XML element name (prefix:name) and marks Namespace entry that this prefix refers to with the [Namespace.Used] flag.

func (Namespace) MarkUsedPrefix

func (ns Namespace) MarkUsedPrefix(prefix string)

MarkUsedPrefix marks Namespace entry with the specified prefix with the [Namespace.Used] flag.

type XMLErr

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

XMLErr represents error, related to the XML processing.

It consist of the arbitrary underlying error and XML path to the problematic Element or Attr.

func (XMLErr) Error

func (xe XMLErr) Error() string

Error returns error string.

func (XMLErr) Unwrap

func (xe XMLErr) Unwrap() error

Unwrap "unwraps" the error.

It returns the underlying error (of its original type), undoing effect of all preceding wrapping with the XMLErrWrap, XMLErrWrapAttr and XMLErrWrapName functions.

Jump to

Keyboard shortcuts

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