mxj

package module
v0.0.0-...-70c0fae Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2014 License: BSD-3-Clause Imports: 11 Imported by: 9 modules, 9 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Marshal/Unmarshal XML to/from JSON and map[string]interface{} values, and extract values from maps by key or key-path, including wildcards.  

**This fork of mxj doesn't prepend attributes with hyphens. **

mxj supplants the legacy x2j and j2x packages. If you want the old syntax, just uncomment the content of x2j.go or j2x.go, which are included as part of this package.

SUMMARY

   type Map map[string]interface{}

   Create a Map value, 'm', from any map[string]interface{} value, 'v':
      m := Map(v)

   Unmarshal / marshal XML as a Map value, 'm':
      m, err := NewMapXml(xmlValue) // unmarshal
      xmlValue, err := m.Xml()      // marshal

   Unmarshal XML from an io.Reader as a Map value, 'm':
      m, err := NewMapReader(xmlReader)         // repeated calls, as with an os.File Reader, will process stream
      m, raw, err := NewMapReaderRaw(xmlReader) // 'raw' points to the raw XML that was decoded

   Marshal Map value, 'm', to an XML Writer (io.Writer):
      err := m.XmlWriter(xmlWriter)         // or: m.XmlIndentWriter(xmlWriter, prefix, indent)
      err, raw := m.XmlWriterRaw(xmlWriter) // 'raw' points to the raw XML that was written on xmlWriter

   Bulk process XML with error handling (note: handlers must return a boolean value):
      err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error))
      err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, *[]byte), errHandler(error, *[]byte))

   Converting XML to JSON: see Examples for NewMapXml and HandleXmlReader.

   There are comparable functions and methods for JSON processing.

   Arbitrary structure values can be decoded to / encoded from Map values:
      m, err := NewMapStruct(structVal)
      err := m.Struct(structPointer)

   To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON
   or structure to a Map value, 'm', or cast a map[string]interface{} value to a Map value, 'm', then:
      paths := m.PathsForKey(key)
      path := m.PathForKeyShortest(key)
      values, err := m.ValuesForKey(key, subkeys)
      values, err := m.ValuesForPath(path, subkeys)
      count, err := m.UpdateValuesForPath(newVal, path, subkeys)

   A new Map with whatever keys are desired can be created from the current Map and then encoded in XML
   or JSON. (Note: keys can use dot-notation.)
      newMap := m.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N")
      newXml := newMap.Xml()   // for example
      newJson := newMap.Json() // ditto

USAGE

The package is fairly well self-documented with examples. (http://godoc.org/github.com/clbanning/mxj)

Also, the subdirectory "examples" contains a wide range of examples, several taken from golang-nuts discussions.

XML PARSING CONVENTIONS

   - Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-',
     to the attribute label.
   - If the element is a simple element and has attributes, the element value
     is given the key '#text' for its map[string]interface{} representation.  (See
     the 'atomFeedString.xml' test data, below.)

RUNNING "GO TEST"

Because there are no guarantees on the sequence map elements are retrieved, the tests have been 
written for visual verification in most cases.  One advantage is that you can easily use the 
output from running "go test" as examples of calling the various functions and methods.

MOTIVATION

I make extensive use of JSON for messaging and typically unmarshal the messages into
map[string]interface{} variables.  This is easily done using json.Unmarshal from the
standard Go libraries.  Unfortunately, many legacy solutions use structured
XML messages; in those environments the applications would have to be refitted to
interoperate with my components.

The better solution is to just provide an alternative HTTP handler that receives
XML doc messages and parses it into a map[string]interface{} variable and then reuse
all the JSON-based code.  The Go xml.Unmarshal() function does not provide the same
option of unmarshaling XML messages into map[string]interface{} variables. So I wrote
a couple of small functions to fill this gap and released them as the x2j package.

Over the next year and a half additional features were added, and the companion j2x
package was released to address XML encoding of arbitrary JSON and map[string]interface{}
values.  As part of a refactoring of our production system and looking at how we'd been
using the x2j and j2x packages we found that we rarely performed direct XML-to-JSON or
JSON-to_XML conversion and that working with the XML or JSON as map[string]interface{}
values was the primary value.  Thus, everything was refactored into the mxj package.

Documentation

Overview

Marshal/Unmarshal XML to/from JSON and map[string]interface{} values, and extract values from maps by key or key-path, including wildcards.

mxj supplants the legacy x2j and j2x packages. If you want the old syntax, just uncomment the content of x2j.go or j2x.go, which are included as part of this package.

SUMMARY

type Map map[string]interface{}

Create a Map value, 'm', from any map[string]interface{} value, 'v':
	m := Map(v)

Unmarshal / marshal XML as a Map value, 'm':
	m, err := NewMapXml(xmlValue) // unmarshal
	xmlValue, err := m.Xml()      // marshal

Unmarshal XML from an io.Reader as a Map value, 'm':
	m, err := NewMapReader(xmlReader)         // repeated calls, as with an os.File Reader, will process stream
	m, raw, err := NewMapReaderRaw(xmlReader) // 'raw' points to the raw XML that was decoded

Marshal Map value, 'm', to an XML Writer (io.Writer):
	err := m.XmlWriter(xmlWriter)         // or: m.XmlIndentWriter(xmlWriter, prefix, indent)
	err, raw := m.XmlWriterRaw(xmlWriter) // 'raw' points to the raw XML that was written on xmlWriter

Bulk process XML with error handling:
	err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error))
	err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, *[]byte), errHandler(error, *[]byte))

Converting XML to JSON: see Examples for NewMapXml and HandleXmlReader.

There are comparable functions and methods for JSON processing.

Arbitrary structure values can be decoded to / encoded from Map values:
	m, err := NewMapStruct(structVal)
	err := m.Struct(structPointer)

To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON
or structure to a Map value, 'm', or cast a map[string]interface{} value to a Map value, 'm', then:
	paths := m.PathsForKey(key)
	path := m.PathForKeyShortest(key)
	values, err := m.ValuesForKey(key, subkeys)
	values, err := m.ValuesForPath(path, subkeys)
	count, err := m.UpdateValuesForPath(newVal, path, subkeys)

A new Map with whatever keys are desired can be created from the current Map and then encoded in XML
or JSON. (Note: keys can use dot-notation.)
	newMap := m.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N")
	newXml := newMap.Xml()     // for example
	newJson := newMap.Json()   // ditto

XML PARSING CONVENTIONS

  • Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-', to the attribute label.
  • If the element is a simple element and has attributes, the element value is given the key '#text' for its map[string]interface{} representation.

Index

Examples

Constants

View Source
const (
	Cast         = true // for clarity - e.g., mxj.NewMapXml(doc, mxj.Cast)
	SafeEncoding = true // ditto - e.g., mv.Json(mxj.SafeEncoding)
)
View Source
const (
	DefaultRootTag = "doc"
)

Variables

View Source
var XmlCharsetReader func(charset string, input io.Reader) (io.Reader, error)

If XmlCharsetReader != nil, it will be used to decode the XML, if required.

  import (
	     charset "code.google.com/p/go-charset/charset"
	     github.com/clbanning/mxj
	 )
  ...
  mu.XmlCharsetReader = charset.NewReader
  m, merr := mu.NewMapXml(xmlValue)

Functions

func HandleJsonReader

func HandleJsonReader(jsonReader io.Reader, mapHandler func(Map) bool, errHandler func(error) bool) error

Bulk process JSON using handlers that process a Map value.

'rdr' is an io.Reader for the JSON (stream).
'mapHandler' is the Map processing handler. Return of 'false' stops further processing.
'errHandler' is the error. Return of 'false' stop processing and returns error.
Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized.
      This means that you can stop reading the file on error or after processing a particular message.
      To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return true.
Example
package main

import ()

func main() {
	/*
		See: bulk_test.go for working example.
		Run "go test" in package directory then scroll back to find output.

		Basic logic for bulk JSON to XML processing is similar to that for
		bulk XML to JSON processing as outlined in the HandleXmlReader example.
		The test case is also a good example.
	*/
}

func HandleJsonReaderRaw

func HandleJsonReaderRaw(jsonReader io.Reader, mapHandler func(Map, *[]byte) bool, errHandler func(error, *[]byte) bool) error

Bulk process JSON using handlers that process a Map value and the raw JSON.

'rdr' is an io.Reader for the JSON (stream).
'mapHandler' is the Map and raw JSON - *[]byte - processing handler. Return of 'false' stops further processing.
'errHandler' is the error and raw JSON processing handler. Return of err != nil stop processing and returns error.
Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized.
      This means that you can stop reading the file on error or after processing a particular message.
      To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return true.
Example
package main

import ()

func main() {
	/*
		See: bulkraw_test.go for working example.
		Run "go test" in package directory then scroll back to find output.

		Basic logic for bulk JSON to XML processing is similar to that for
		bulk XML to JSON processing as outlined in the HandleXmlReader example.
		The test case is also a good example.
	*/
}

func HandleXmlReader

func HandleXmlReader(xmlReader io.Reader, mapHandler func(Map) bool, errHandler func(error) bool) error

Bulk process XML using handlers that process a Map value.

'rdr' is an io.Reader for XML (stream)
'mapHandler' is the Map processing handler. Return of 'false' stops further processing.
'errHandler' is the error processing handler. Return of 'false' stops further processing and returns the error.
Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized.
      This means that you can stop reading the file on error or after processing a particular message.
      To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return true.
Example
package main

import ()

func main() {
	/*
		Bulk processing XML to JSON seems to be a common requirement.
		See: bulk_test.go for working example.
		     Run "go test" in package directory then scroll back to find output.

		The logic is as follows.

			// need somewhere to write the JSON.
			var jsonWriter io.Writer

			// probably want to log any errors in reading the XML stream
			var xmlErrLogger io.Writer

			// func to handle Map value from XML Reader
			func maphandler(m mxj.Map) bool {
				// marshal Map as JSON
				jsonVal, err := m.Json()
				if err != nil {
					// log error
					return false // stops further processing of XML Reader
				}

				// write JSON somewhere
				_, err = jsonWriter.Write(jsonVal)
				if err != nil {
					// log error
					return false // stops further processing of XML Reader
				}

				// continue - get next XML from Reader
				return true
			}

			// func to handle error from unmarshaling XML Reader
			func errhandler(errVal error) bool {
				// log error somewhere
				_, err := xmlErrLogger.Write([]byte(errVal.Error()))
				if err != nil {
					// log error
					return false // stops further processing of XML Reader
				}

				// continue processing
				return true
			}

			// func that starts bulk processing of the XML
				...
				// set up io.Reader for XML data - perhaps an os.File
				...
				err := mxj.HandleXmlReader(xmlReader, maphandler, errhandler)
				if err != nil {
					// handle error
				}
				...
	*/
}

func HandleXmlReaderRaw

func HandleXmlReaderRaw(xmlReader io.Reader, mapHandler func(Map, *[]byte) bool, errHandler func(error, *[]byte) bool) error

Bulk process XML using handlers that process a Map value and the raw XML.

'rdr' is an io.Reader for XML (stream)
'mapHandler' is the Map and raw XML - *[]byte - processing handler. Return of 'false' stops further processing.
'errHandler' is the error and raw XML processing handler. Return of 'false' stops further processing and returns the error.
Note: mapHandler() and errHandler() calls are blocking, so reading and processing of messages is serialized.
      This means that you can stop reading the file on error or after processing a particular message.
      To have reading and handling run concurrently, pass argument(s) to a go routine in handler and return true.
See NewMapXmlReaderRaw for comment on performance associated with retrieving raw XML from a Reader.
Example
package main

import ()

func main() {
	/*
		See: bulkraw_test.go for working example.
		Run "go test" in package directory then scroll back to find output.

		Basic logic for bulk XML to JSON processing is in HandleXmlReader example;
		the only major difference is in handler function signatures so they are passed
		the raw XML.  (Read documentation on NewXmlReader regarding performance.)
	*/
}

func XmlDefaultEmptyElemSyntax

func XmlDefaultEmptyElemSyntax()

XmlDefaultEmptyElemSyntax() - <tag .../> rather than <tag ...></tag>. Return XML encoding for empty elements to the default package setting. Reverses effect of XmlGoEmptyElemSyntax().

func XmlGoEmptyElemSyntax

func XmlGoEmptyElemSyntax()

XmlGoEmptyElemSyntax() - <tag ...></tag> rather than <tag .../>.

Go's encoding/xml package marshals empty XML elements as <tag ...></tag>.  By default this package
encodes empty elements as <tag .../>.  If you're marshaling Map values that include structures
(which are passed to xml.Marshal for encoding), this will let you conform to the standard package.

Alternatively, you can replace the encoding/xml/marshal.go file in the standard libary with the
patched version in the "xml_marshal" folder in this package. Then use xml.SetUseNullEndTag(true)
to have all XML encoding use <tag .../> for empty elements.

Types

type Map

type Map map[string]interface{}

func New

func New() Map

Allocate a Map.

func NewMapJson

func NewMapJson(jsonVal []byte) (Map, error)

Just a wrapper on json.Unmarshal

Converting JSON to XML is a simple as:
	...
	mapVal, merr := mxj.NewMapJson(jsonVal)
	if merr != nil {
		// handle error
	}
	xmlVal, xerr := mapVal.Xml()
	if xerr != nil {
		// handle error
	}

func NewMapJsonReader

func NewMapJsonReader(jsonReader io.Reader) (Map, error)

Retrieve a Map value from an io.Reader.

func NewMapJsonReaderRaw

func NewMapJsonReaderRaw(jsonReader io.Reader) (Map, *[]byte, error)

Retrieve a Map value and raw JSON - *[]byte - from an io.Reader.

func NewMapStruct

func NewMapStruct(structVal interface{}) (Map, error)

Create a new Map value from a structure. Error returned if argument is not a structure or a pointer or if there is a json.Marshal or json.Unmarshal error.

Only public structure fields are decoded in the Map value. Also, json.Marshal structure encoding rules
are followed for decoding the structure fields.
Example
package main

import (
	"fmt"
	"github.com/clbanning/mxj"
)

func main() {
	type str struct {
		IntVal   int     `json:"int"`
		StrVal   string  `json:"str"`
		FloatVal float64 `json:"float"`
		BoolVal  bool    `json:"bool"`
		private  string
	}
	strVal := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "Skies are blue"}

	mapVal, merr := mxj.NewMapStruct(strVal)
	if merr != nil {
		// handle error
	}

	fmt.Printf("strVal: %#v\n", strVal)
	fmt.Printf("mapVal: %#v\n", mapVal)
	// Note: example output is conformed to pass "go test".  "mxj_test" is example_test.go package name.

}
Output:
strVal: mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
mapVal: mxj.Map{"int":4, "str":"now's the time", "float":3.14159, "bool":true}

func NewMapXml

func NewMapXml(xmlVal []byte, cast ...bool) (Map, error)

NewMapXml - convert an XML doc into a Map (This is analogous to unmarshalling a JSON string to map[string]interface{} using json.Unmarshal().)

If the optional argument 'cast' is 'true', then values will be converted to boolean or float64 if possible.

Converting XML to JSON is a simple as:
	...
	mapVal, merr := mxj.NewMapXml(xmlVal)
	if merr != nil {
		// handle error
	}
	jsonVal, jerr := mapVal.Json()
	if jerr != nil {
		// handle error
	}

func NewMapXmlReader

func NewMapXmlReader(xmlReader io.Reader, cast ...bool) (Map, error)

Get next XML doc from an io.Reader as a Map value. Returns Map value.

func NewMapXmlReaderRaw

func NewMapXmlReaderRaw(xmlReader io.Reader, cast ...bool) (Map, *[]byte, error)

Get next XML doc from an io.Reader as a Map value. Returns Map value and pointer to raw XML.

NOTE: Due to the implementation of xml.Decoder, the raw XML off the reader is buffered to *[]byte
      using a ByteReader. If the io.Reader is an os.File, there may be significant performance impact.
      See the examples - getmetrics1.go through getmetrics4.go - for comparative use cases on a large
      data set. If the io.Reader is wrapping a []byte value in-memory, however, such as http.Request.Body
      you CAN use it to efficiently unmarshal an XML and retrieve the raw XML in a single call.

func (Map) Json

func (mv Map) Json(safeEncoding ...bool) ([]byte, error)

Just a wrapper on json.Marshal. If option safeEncoding is'true' then safe encoding of '<', '>' and '&' is preserved. (see encoding/json#Marshal, encoding/json#Encode)

func (Map) JsonIndent

func (mv Map) JsonIndent(prefix, indent string, safeEncoding ...bool) ([]byte, error)

Just a wrapper on json.MarshalIndent. If option safeEncoding is'true' then safe encoding of '<' , '>' and '&' is preserved. (see encoding/json#Marshal, encoding/json#Encode)

func (Map) JsonIndentWriter

func (mv Map) JsonIndentWriter(jsonWriter io.Writer, prefix, indent string, safeEncoding ...bool) error

Writes the Map as pretty JSON on the Writer. If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.

func (Map) JsonIndentWriterRaw

func (mv Map) JsonIndentWriterRaw(jsonWriter io.Writer, prefix, indent string, safeEncoding ...bool) (*[]byte, error)

Writes the Map as pretty JSON on the Writer. *[]byte is the raw JSON that was written. If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.

func (Map) JsonWriter

func (mv Map) JsonWriter(jsonWriter io.Writer, safeEncoding ...bool) error

Writes the Map as JSON on the Writer. If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.

func (Map) JsonWriterRaw

func (mv Map) JsonWriterRaw(jsonWriter io.Writer, safeEncoding ...bool) (*[]byte, error)

Writes the Map as JSON on the Writer. *[]byte is the raw JSON that was written. If 'safeEncoding' is 'true', then "safe" encoding of '<', '>' and '&' is preserved.

func (Map) NewMap

func (mv Map) NewMap(keypairs ...string) (Map, error)

(Map)NewMap - create a new Map from data in the current Map.

'keypairs' are key mappings "oldKey:newKey" that specify that the current value of 'oldKey'
should be the value for 'newKey' in the returned Map.
	- 'oldKey' supports dot-notation as described for (Map)ValuesForPath()
	- 'newKey' supports dot-notation with the exception of the wildcard, '*', character
	- "oldKey" is shorthand for for the keypair value "oldKey:oldKey"
	- "oldKey:" and ":newKey" are invalid keypair values
	- if 'oldKey' does not exist in the current Map, it is not written to the new Map.
	  "null" is not supported unless it is the current Map.
	- see newmap_test.go for several syntax examples

NOTE: mv.NewMap() == mxj.New().

func (Map) Old

func (mv Map) Old() map[string]interface{}

Cast a Map to map[string]interface{}

func (Map) PathForKeyShortest

func (mv Map) PathForKeyShortest(key string) string

Extract the shortest path from all possible paths - from PathsForKey() - in Map, 'mv'.. Paths are strings using dot-notation.

func (Map) PathsForKey

func (mv Map) PathsForKey(key string) []string

Get all paths through Map, 'mv', (in dot-notation) that terminate with the specified key. Results can be used with ValuesForPath.

func (Map) StringIndent

func (mv Map) StringIndent(offset ...int) string

Pretty print a Map.

func (Map) Struct

func (mv Map) Struct(structPtr interface{}) error

Marshal a map[string]interface{} into a structure referenced by 'structPtr'. Error returned if argument is not a pointer or if json.Unmarshal returns an error.

json.Unmarshal structure encoding rules are followed to encode public structure fields.
Example
package main

import (
	"fmt"
	"github.com/clbanning/mxj"
)

func main() {
	type str struct {
		IntVal   int     `json:"int"`
		StrVal   string  `json:"str"`
		FloatVal float64 `json:"float"`
		BoolVal  bool    `json:"bool"`
		private  string
	}

	mapVal := mxj.Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true, "private": "Somewhere over the rainbow"}

	var strVal str
	mverr := mapVal.Struct(&strVal)
	if mverr != nil {
		// handle error
	}

	fmt.Printf("mapVal: %#v\n", mapVal)
	fmt.Printf("strVal: %#v\n", strVal)
	// Note: example output is conformed to pass "go test".  "mxj_test" is example_test.go package name.

}
Output:
mapVal: mxj.Map{"int":4, "str":"now's the time", "float":3.14159, "bool":true, "private":"Somewhere over the rainbow"}
strVal: mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:""}

func (Map) UpdateValuesForPath

func (mv Map) UpdateValuesForPath(newVal interface{}, path string, subkeys ...string) (int, error)

Update value based on path and possible sub-key values. A count of the number of values changed and any error are returned. If the count == 0, then no path (and subkeys) matched.

'newVal' can be a Map or map[string]interface{} value with a single 'key' that is the key to be modified
             or a string value "key:value[:type]" where type is "bool" or "num" to cast the value.
'path' is dot-notation list of keys to traverse; last key in path can be newVal key
'subkeys' are "key:value[:type]" entries that must match for path node
            The subkey can be wildcarded - "key:*" - to require that it's there with some value.
            If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an
            exclusion critera - e.g., "!author:William T. Gaddis".
Example
package main

import ()

func main() {
	/*
	   var biblioDoc = []byte(`
	   <biblio>

	   	<author>
	   		<name>William Gaddis</name>
	   		<books>
	   			<book>
	   				<title>The Recognitions</title>
	   				<date>1955</date>
	   				<review>A novel that changed the face of American literature.</review>
	   			</book>
	   			<book>
	   				<title>JR</title>
	   				<date>1975</date>
	   				<review>Winner of National Book Award for Fiction.</review>
	   			</book>
	   		</books>
	   	</author>

	   </biblio>`)

	   	...
	   	m, merr := mxj.NewMapXml(biblioDoc)
	   	if merr != nil {
	   		// handle error
	   	}

	   	// change 'review' for a book
	   	count, err := m.UpdateValuesForPath("review:National Book Award winner." "*.*.*.*", "title:JR")
	   	if err != nil {
	   		// handle error
	   	}
	   	...

	   	// change 'date' value from string type to float64 type
	   	// Note: the following is equivalent to m, merr := NewMapXml(biblioDoc, mxj.Cast).
	   	path := m.PathForKeyShortest("date")
	   	v, err := m.ValuesForPath(path)
	   	if err != nil {
	   		// handle error
	   	}
	   	var total int
	   	for _, vv := range v {
	   		oldVal := "date:" + vv.(string)
	   		newVal := "date:" + vv.(string) + ":num"
	   		n, err := m.UpdateValuesForPath(newVal, path, oldVal)
	   		if err != nil {
	   			// handle error
	   		}
	   		total += n
	   	}
	   	...
	*/
}

func (Map) ValuesForKey

func (mv Map) ValuesForKey(key string, subkeys ...string) ([]interface{}, error)

Return all values in Map, 'mv', associated with a 'key'. If len(returned_values) == 0, then no match. On error, the returned array is 'nil'. NOTE: 'key' can be wildcard, "*".

  'subkeys' (optional) are "key:val[:type]" strings representing attributes or elements in a list.
		         By default 'val' is of type string. "key:val:bool" and "key:val:float" to coerce them.
		         For attributes prefix the label with a hyphen, '-', e.g., "-seq:3".
		         If the 'key' refers to a list, then "key:value" could select a list member of the list.
	            The subkey can be wildcarded - "key:*" - to require that it's there with some value.
	            If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an
	            exclusion critera - e.g., "!author:William T. Gaddis".

func (Map) ValuesForPath

func (mv Map) ValuesForPath(path string, subkeys ...string) ([]interface{}, error)

Retrieve all values for a path from the Map. If len(returned_values) == 0, then no match. On error, the returned array is 'nil'.

  'path' is a dot-separated path of key values. If a node in the path is '*', then everything beyond is walked.
  'subkeys' (optional) are "key:val[:type]" strings representing attributes or elements in a list.
		         By default 'val' is of type string. "key:val:bool" and "key:val:float" to coerce them.
		         For attributes prefix the label with a hyphen, '-', e.g., "-seq:3".
		         If the 'path' refers to a list, then "tag:value" would select a list member of the list.
	            The subkey can be wildcarded - "key:*" - to require that it's there with some value.
	            If a subkey is preceeded with the '!' character, the key:value[:type] entry is treated as an
	            exclusion critera - e.g., "!author:William T. Gaddis".

func (Map) Xml

func (mv Map) Xml(rootTag ...string) ([]byte, error)

Encode a Map as XML. The companion of NewMapXml(). The following rules apply.

  • The key label "#text" is treated as the value for a simple element with attributes.
  • Map keys that begin with a hyphen, '-', are interpreted as attributes. It is an error if the attribute doesn't have a []byte, string, number, or boolean value.
  • Map value type encoding: > string, bool, float64, int, int32, int64, float32: per "%v" formating > []bool, []uint8: by casting to string > structures, etc.: handed to xml.Marshal() - if there is an error, the element value is "UNKNOWN"
  • Elements with only attribute values or are null are terminated using "/>".
  • If len(mv) == 1 and no rootTag is provided, then the map key is used as the root tag. Thus, `{ "key":"value" }` encodes as "<key>value</key>".
  • To encode empty elements in a syntax consistent with encoding/xml call UseGoXmlEmptyElementSyntax().

func (Map) XmlIndent

func (mv Map) XmlIndent(prefix, indent string, rootTag ...string) ([]byte, error)

Encode a map[string]interface{} as a pretty XML string. See Xml for encoding rules.

func (Map) XmlIndentWriter

func (mv Map) XmlIndentWriter(xmlWriter io.Writer, prefix, indent string, rootTag ...string) error

Writes the Map as pretty XML on the Writer. See Xml() for encoding rules.

func (Map) XmlIndentWriterRaw

func (mv Map) XmlIndentWriterRaw(xmlWriter io.Writer, prefix, indent string, rootTag ...string) (*[]byte, error)

Writes the Map as pretty XML on the Writer. *[]byte is the raw XML that was written. See Xml() for encoding rules.

func (Map) XmlWriter

func (mv Map) XmlWriter(xmlWriter io.Writer, rootTag ...string) error

Writes the Map as XML on the Writer. See Xml() for encoding rules.

func (Map) XmlWriterRaw

func (mv Map) XmlWriterRaw(xmlWriter io.Writer, rootTag ...string) (*[]byte, error)

Writes the Map as XML on the Writer. *[]byte is the raw XML that was written. See Xml() for encoding rules.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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