...

Text file src/github.com/clbanning/mxj/v2/readme.md

Documentation: github.com/clbanning/mxj/v2

     1<h2>mxj - to/from maps, XML and JSON</h2>
     2Decode/encode XML to/from map[string]interface{} (or JSON) values, and extract/modify values from maps by key or key-path, including wildcards.
     3
     4mxj supplants the legacy x2j and j2x packages. If you want the old syntax, use mxj/x2j and mxj/j2x packages.
     5
     6<h4>Installation</h4>
     7Using go.mod:
     8<pre>
     9go get github.com/clbanning/mxj/v2@v2.7	
    10</pre>
    11
    12<pre>
    13import "github.com/clbanning/mxj/v2"
    14</pre>
    15
    16... or just vendor the package.
    17
    18<h4>Related Packages</h4>
    19
    20https://github.com/clbanning/checkxml provides functions for validating XML data.
    21
    22<h4>Refactor Encoder - 2020.05.01</h4>
    23Issue #70 highlighted that encoding large maps does not scale well, since the original logic used string appends operations. Using bytes.Buffer results in linear scaling for very large XML docs. (Metrics based on MacBook Pro i7 w/ 16 GB.)
    24
    25	Nodes      m.XML() time
    26	54809       12.53708ms
    27	109780      32.403183ms
    28	164678      59.826412ms
    29	482598     109.358007ms
    30
    31<h4>Refactor Decoder - 2015.11.15</h4>
    32For over a year I've wanted to refactor the XML-to-map[string]interface{} decoder to make it more performant.  I recently took the time to do that, since we were using github.com/clbanning/mxj in a production system that could be deployed on a Raspberry Pi.  Now the decoder is comparable to the stdlib JSON-to-map[string]interface{} decoder in terms of its additional processing overhead relative to decoding to a structure value.  As shown by:
    33
    34	BenchmarkNewMapXml-4         	  100000	     18043 ns/op
    35	BenchmarkNewStructXml-4      	  100000	     14892 ns/op
    36	BenchmarkNewMapJson-4        	  300000	      4633 ns/op
    37	BenchmarkNewStructJson-4     	  300000	      3427 ns/op
    38	BenchmarkNewMapXmlBooks-4    	   20000	     82850 ns/op
    39	BenchmarkNewStructXmlBooks-4 	   20000	     67822 ns/op
    40	BenchmarkNewMapJsonBooks-4   	  100000	     17222 ns/op
    41	BenchmarkNewStructJsonBooks-4	  100000	     15309 ns/op
    42
    43<h4>Notices</h4>
    44
    45	2022.11.28: v2.7 - add SetGlobalKeyMapPrefix to change default prefix, '#', for default keys
    46	2022.11.20: v2.6 - add NewMapForattedXmlSeq for XML docs formatted with whitespace character
    47	2021.02.02: v2.5 - add XmlCheckIsValid toggle to force checking that the encoded XML is valid
    48	2020.12.14: v2.4 - add XMLEscapeCharsDecoder to preserve XML escaped characters in Map values
    49	2020.10.28: v2.3 - add TrimWhiteSpace option
    50	2020.05.01: v2.2 - optimize map to XML encoding for large XML docs.
    51	2019.07.04: v2.0 - remove unnecessary methods - mv.XmlWriterRaw, mv.XmlIndentWriterRaw - for Map and MapSeq.
    52	2019.07.04: Add MapSeq type and move associated functions and methods from Map to MapSeq.
    53	2019.01.21: DecodeSimpleValuesAsMap - decode to map[<tag>:map["#text":<value>]] rather than map[<tag>:<value>]
    54	2018.04.18: mv.Xml/mv.XmlIndent encodes non-map[string]interface{} map values - map[string]string, map[int]uint, etc.
    55	2018.03.29: mv.Gob/NewMapGob support gob encoding/decoding of Maps.
    56	2018.03.26: Added mxj/x2j-wrapper sub-package for migrating from legacy x2j package.
    57	2017.02.22: LeafNode paths can use ".N" syntax rather than "[N]" for list member indexing.
    58	2017.02.10: SetFieldSeparator changes field separator for args in UpdateValuesForPath, ValuesFor... methods.
    59	2017.02.06: Support XMPP stream processing - HandleXMPPStreamTag().
    60	2016.11.07: Preserve name space prefix syntax in XmlSeq parser - NewMapXmlSeq(), etc.
    61	2016.06.25: Support overriding default XML attribute prefix, "-", in Map keys - SetAttrPrefix().
    62	2016.05.26: Support customization of xml.Decoder by exposing CustomDecoder variable.
    63	2016.03.19: Escape invalid chars when encoding XML attribute and element values - XMLEscapeChars().
    64	2016.03.02: By default decoding XML with float64 and bool value casting will not cast "NaN", "Inf", and "-Inf".
    65	            To cast them to float64, first set flag with CastNanInf(true).
    66	2016.02.22: New mv.Root(), mv.Elements(), mv.Attributes methods let you examine XML document structure.
    67	2016.02.16: Add CoerceKeysToLower() option to handle tags with mixed capitalization.
    68	2016.02.12: Seek for first xml.StartElement token; only return error if io.EOF is reached first (handles BOM).
    69	2015.12.02: XML decoding/encoding that preserves original structure of document. See NewMapXmlSeq()
    70	            and mv.XmlSeq() / mv.XmlSeqIndent().
    71	2015-05-20: New: mv.StringIndentNoTypeInfo().
    72	            Also, alphabetically sort map[string]interface{} values by key to prettify output for mv.Xml(),
    73	            mv.XmlIndent(), mv.StringIndent(), mv.StringIndentNoTypeInfo().
    74	2014-11-09: IncludeTagSeqNum() adds "_seq" key with XML doc positional information.
    75	            (NOTE: PreserveXmlList() is similar and will be here soon.)
    76	2014-09-18: inspired by NYTimes fork, added PrependAttrWithHyphen() to allow stripping hyphen from attribute tag.
    77	2014-08-02: AnyXml() and AnyXmlIndent() will try to marshal arbitrary values to XML.
    78	2014-04-28: ValuesForPath() and NewMap() now accept path with indexed array references.
    79
    80<h4>Basic Unmarshal XML to map[string]interface{}</h4>
    81<pre>type Map map[string]interface{}</pre>
    82
    83Create a `Map` value, 'mv', from any `map[string]interface{}` value, 'v':
    84<pre>mv := Map(v)</pre>
    85
    86Unmarshal / marshal XML as a `Map` value, 'mv':
    87<pre>mv, err := NewMapXml(xmlValue) // unmarshal
    88xmlValue, err := mv.Xml()      // marshal</pre>
    89
    90Unmarshal XML from an `io.Reader` as a `Map` value, 'mv':
    91<pre>mv, err := NewMapXmlReader(xmlReader)         // repeated calls, as with an os.File Reader, will process stream
    92mv, raw, err := NewMapXmlReaderRaw(xmlReader) // 'raw' is the raw XML that was decoded</pre>
    93
    94Marshal `Map` value, 'mv', to an XML Writer (`io.Writer`):
    95<pre>err := mv.XmlWriter(xmlWriter)
    96raw, err := mv.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter</pre>
    97   
    98Also, for prettified output:
    99<pre>xmlValue, err := mv.XmlIndent(prefix, indent, ...)
   100err := mv.XmlIndentWriter(xmlWriter, prefix, indent, ...)
   101raw, err := mv.XmlIndentWriterRaw(xmlWriter, prefix, indent, ...)</pre>
   102
   103Bulk process XML with error handling (note: handlers must return a boolean value):
   104<pre>err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error))
   105err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, []byte), errHandler(error, []byte))</pre>
   106
   107Converting XML to JSON: see Examples for `NewMapXml` and `HandleXmlReader`.
   108
   109There are comparable functions and methods for JSON processing.
   110
   111Arbitrary structure values can be decoded to / encoded from `Map` values:
   112<pre>mv, err := NewMapStruct(structVal)
   113err := mv.Struct(structPointer)</pre>
   114
   115<h4>Extract / modify Map values</h4>
   116To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON
   117or structure to a `Map` value, 'mv', or cast a `map[string]interface{}` value to a `Map` value, 'mv', then:
   118<pre>paths := mv.PathsForKey(key)
   119path := mv.PathForKeyShortest(key)
   120values, err := mv.ValuesForKey(key, subkeys)
   121values, err := mv.ValuesForPath(path, subkeys)
   122count, err := mv.UpdateValuesForPath(newVal, path, subkeys)</pre>
   123
   124Get everything at once, irrespective of path depth:
   125<pre>leafnodes := mv.LeafNodes()
   126leafvalues := mv.LeafValues()</pre>
   127
   128A new `Map` with whatever keys are desired can be created from the current `Map` and then encoded in XML
   129or JSON. (Note: keys can use dot-notation.)
   130<pre>newMap, err := mv.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N")
   131newMap, err := mv.NewMap("oldKey1", "oldKey3", "oldKey5") // a subset of 'mv'; see "examples/partial.go"
   132newXml, err := newMap.Xml()   // for example
   133newJson, err := newMap.Json() // ditto</pre>
   134
   135<h4>Usage</h4>
   136
   137The package is fairly well [self-documented with examples](http://godoc.org/github.com/clbanning/mxj).
   138
   139Also, the subdirectory "examples" contains a wide range of examples, several taken from golang-nuts discussions.
   140
   141<h4>XML parsing conventions</h4>
   142
   143Using NewMapXml()
   144
   145   - Attributes are parsed to `map[string]interface{}` values by prefixing a hyphen, `-`,
   146     to the attribute label. (Unless overridden by `PrependAttrWithHyphen(false)` or
   147     `SetAttrPrefix()`.)
   148   - If the element is a simple element and has attributes, the element value
   149     is given the key `#text` for its `map[string]interface{}` representation.  (See
   150     the 'atomFeedString.xml' test data, below.)
   151   - XML comments, directives, and process instructions are ignored.
   152   - If CoerceKeysToLower() has been called, then the resultant keys will be lower case.
   153
   154Using NewMapXmlSeq()
   155
   156   - Attributes are parsed to `map["#attr"]map[<attr_label>]map[string]interface{}`values
   157     where the `<attr_label>` value has "#text" and "#seq" keys - the "#text" key holds the 
   158     value for `<attr_label>`.
   159   - All elements, except for the root, have a "#seq" key.
   160   - Comments, directives, and process instructions are unmarshalled into the Map using the
   161     keys "#comment", "#directive", and "#procinst", respectively. (See documentation for more
   162     specifics.)
   163   - Name space syntax is preserved: 
   164      - `<ns:key>something</ns.key>` parses to `map["ns:key"]interface{}{"something"}`
   165      - `xmlns:ns="http://myns.com/ns"` parses to `map["xmlns:ns"]interface{}{"http://myns.com/ns"}`
   166
   167Both
   168
   169   - By default, "Nan", "Inf", and "-Inf" values are not cast to float64.  If you want them
   170     to be cast, set a flag to cast them  using CastNanInf(true).
   171
   172<h4>XML encoding conventions</h4>
   173
   174   - 'nil' `Map` values, which may represent 'null' JSON values, are encoded as `<tag/>`.
   175     NOTE: the operation is not symmetric as `<tag/>` elements are decoded as `tag:""` `Map` values,
   176           which, then, encode in JSON as `"tag":""` values.
   177   - ALSO: there is no guarantee that the encoded XML doc will be the same as the decoded one.  (Go
   178           randomizes the walk through map[string]interface{} values.) If you plan to re-encode the
   179           Map value to XML and want the same sequencing of elements look at NewMapXmlSeq() and
   180           mv.XmlSeq() - these try to preserve the element sequencing but with added complexity when
   181           working with the Map representation.
   182
   183<h4>Running "go test"</h4>
   184
   185Because there are no guarantees on the sequence map elements are retrieved, the tests have been 
   186written for visual verification in most cases.  One advantage is that you can easily use the 
   187output from running "go test" as examples of calling the various functions and methods.
   188
   189<h4>Motivation</h4>
   190
   191I make extensive use of JSON for messaging and typically unmarshal the messages into
   192`map[string]interface{}` values.  This is easily done using `json.Unmarshal` from the
   193standard Go libraries.  Unfortunately, many legacy solutions use structured
   194XML messages; in those environments the applications would have to be refactored to
   195interoperate with my components.
   196
   197The better solution is to just provide an alternative HTTP handler that receives
   198XML messages and parses it into a `map[string]interface{}` value and then reuse
   199all the JSON-based code.  The Go `xml.Unmarshal()` function does not provide the same
   200option of unmarshaling XML messages into `map[string]interface{}` values. So I wrote
   201a couple of small functions to fill this gap and released them as the x2j package.
   202
   203Over the next year and a half additional features were added, and the companion j2x
   204package was released to address XML encoding of arbitrary JSON and `map[string]interface{}`
   205values.  As part of a refactoring of our production system and looking at how we had been
   206using the x2j and j2x packages we found that we rarely performed direct XML-to-JSON or
   207JSON-to_XML conversion and that working with the XML or JSON as `map[string]interface{}`
   208values was the primary value.  Thus, everything was refactored into the mxj package.
   209

View as plain text