doc.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. // mxj - A collection of map[string]interface{} and associated XML and JSON utilities.
  2. // Copyright 2012-2019, Charles Banning. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file
  5. /*
  6. Marshal/Unmarshal XML to/from map[string]interface{} values (and JSON); extract/modify values from maps by key or key-path, including wildcards.
  7. mxj supplants the legacy x2j and j2x packages. The subpackage x2j-wrapper is provided to facilitate migrating from the x2j package. The x2j and j2x subpackages provide similar functionality of the old packages but are not function-name compatible with them.
  8. Note: this library was designed for processing ad hoc anonymous messages. Bulk processing large data sets may be much more efficiently performed using the encoding/xml or encoding/json packages from Go's standard library directly.
  9. Related Packages:
  10. checkxml: github.com/clbanning/checkxml provides functions for validating XML data.
  11. Notes:
  12. 2022.11.28: v2.7 - add SetGlobalKeyMapPrefix to change default prefix, '#', for default keys
  13. 2022.11.20: v2.6 - add NewMapForattedXmlSeq for XML docs formatted with whitespace character
  14. 2021.02.02: v2.5 - add XmlCheckIsValid toggle to force checking that the encoded XML is valid
  15. 2020.12.14: v2.4 - add XMLEscapeCharsDecoder to preserve XML escaped characters in Map values
  16. 2020.10.28: v2.3 - add TrimWhiteSpace option
  17. 2020.05.01: v2.2 - optimize map to XML encoding for large XML docs.
  18. 2019.07.04: v2.0 - remove unnecessary methods - mv.XmlWriterRaw, mv.XmlIndentWriterRaw - for Map and MapSeq.
  19. 2019.07.04: Add MapSeq type and move associated functions and methods from Map to MapSeq.
  20. 2019.01.21: DecodeSimpleValuesAsMap - decode to map[<tag>:map["#text":<value>]] rather than map[<tag>:<value>].
  21. 2018.04.18: mv.Xml/mv.XmlIndent encodes non-map[string]interface{} map values - map[string]string, map[int]uint, etc.
  22. 2018.03.29: mv.Gob/NewMapGob support gob encoding/decoding of Maps.
  23. 2018.03.26: Added mxj/x2j-wrapper sub-package for migrating from legacy x2j package.
  24. 2017.02.22: LeafNode paths can use ".N" syntax rather than "[N]" for list member indexing.
  25. 2017.02.21: github.com/clbanning/checkxml provides functions for validating XML data.
  26. 2017.02.10: SetFieldSeparator changes field separator for args in UpdateValuesForPath, ValuesFor... methods.
  27. 2017.02.06: Support XMPP stream processing - HandleXMPPStreamTag().
  28. 2016.11.07: Preserve name space prefix syntax in XmlSeq parser - NewMapXmlSeq(), etc.
  29. 2016.06.25: Support overriding default XML attribute prefix, "-", in Map keys - SetAttrPrefix().
  30. 2016.05.26: Support customization of xml.Decoder by exposing CustomDecoder variable.
  31. 2016.03.19: Escape invalid chars when encoding XML attribute and element values - XMLEscapeChars().
  32. 2016.03.02: By default decoding XML with float64 and bool value casting will not cast "NaN", "Inf", and "-Inf".
  33. To cast them to float64, first set flag with CastNanInf(true).
  34. 2016.02.22: New mv.Root(), mv.Elements(), mv.Attributes methods let you examine XML document structure.
  35. 2016.02.16: Add CoerceKeysToLower() option to handle tags with mixed capitalization.
  36. 2016.02.12: Seek for first xml.StartElement token; only return error if io.EOF is reached first (handles BOM).
  37. 2015-12-02: NewMapXmlSeq() with mv.XmlSeq() & co. will try to preserve structure of XML doc when re-encoding.
  38. 2014-08-02: AnyXml() and AnyXmlIndent() will try to marshal arbitrary values to XML.
  39. SUMMARY
  40. type Map map[string]interface{}
  41. Create a Map value, 'mv', from any map[string]interface{} value, 'v':
  42. mv := Map(v)
  43. Unmarshal / marshal XML as a Map value, 'mv':
  44. mv, err := NewMapXml(xmlValue) // unmarshal
  45. xmlValue, err := mv.Xml() // marshal
  46. Unmarshal XML from an io.Reader as a Map value, 'mv':
  47. mv, err := NewMapXmlReader(xmlReader) // repeated calls, as with an os.File Reader, will process stream
  48. mv, raw, err := NewMapXmlReaderRaw(xmlReader) // 'raw' is the raw XML that was decoded
  49. Marshal Map value, 'mv', to an XML Writer (io.Writer):
  50. err := mv.XmlWriter(xmlWriter)
  51. raw, err := mv.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter
  52. Also, for prettified output:
  53. xmlValue, err := mv.XmlIndent(prefix, indent, ...)
  54. err := mv.XmlIndentWriter(xmlWriter, prefix, indent, ...)
  55. raw, err := mv.XmlIndentWriterRaw(xmlWriter, prefix, indent, ...)
  56. Bulk process XML with error handling (note: handlers must return a boolean value):
  57. err := HandleXmlReader(xmlReader, mapHandler(Map), errHandler(error))
  58. err := HandleXmlReaderRaw(xmlReader, mapHandler(Map, []byte), errHandler(error, []byte))
  59. Converting XML to JSON: see Examples for NewMapXml and HandleXmlReader.
  60. There are comparable functions and methods for JSON processing.
  61. Arbitrary structure values can be decoded to / encoded from Map values:
  62. mv, err := NewMapStruct(structVal)
  63. err := mv.Struct(structPointer)
  64. To work with XML tag values, JSON or Map key values or structure field values, decode the XML, JSON
  65. or structure to a Map value, 'mv', or cast a map[string]interface{} value to a Map value, 'mv', then:
  66. paths := mv.PathsForKey(key)
  67. path := mv.PathForKeyShortest(key)
  68. values, err := mv.ValuesForKey(key, subkeys)
  69. values, err := mv.ValuesForPath(path, subkeys) // 'path' can be dot-notation with wildcards and indexed arrays.
  70. count, err := mv.UpdateValuesForPath(newVal, path, subkeys)
  71. Get everything at once, irrespective of path depth:
  72. leafnodes := mv.LeafNodes()
  73. leafvalues := mv.LeafValues()
  74. A new Map with whatever keys are desired can be created from the current Map and then encoded in XML
  75. or JSON. (Note: keys can use dot-notation. 'oldKey' can also use wildcards and indexed arrays.)
  76. newMap, err := mv.NewMap("oldKey_1:newKey_1", "oldKey_2:newKey_2", ..., "oldKey_N:newKey_N")
  77. newMap, err := mv.NewMap("oldKey1", "oldKey3", "oldKey5") // a subset of 'mv'; see "examples/partial.go"
  78. newXml, err := newMap.Xml() // for example
  79. newJson, err := newMap.Json() // ditto
  80. XML PARSING CONVENTIONS
  81. Using NewMapXml()
  82. - Attributes are parsed to `map[string]interface{}` values by prefixing a hyphen, `-`,
  83. to the attribute label. (Unless overridden by `PrependAttrWithHyphen(false)` or
  84. `SetAttrPrefix()`.)
  85. - If the element is a simple element and has attributes, the element value
  86. is given the key `#text` for its `map[string]interface{}` representation. (See
  87. the 'atomFeedString.xml' test data, below.)
  88. - XML comments, directives, and process instructions are ignored.
  89. - If CoerceKeysToLower() has been called, then the resultant keys will be lower case.
  90. Using NewMapXmlSeq()
  91. - Attributes are parsed to `map["#attr"]map[<attr_label>]map[string]interface{}`values
  92. where the `<attr_label>` value has "#text" and "#seq" keys - the "#text" key holds the
  93. value for `<attr_label>`.
  94. - All elements, except for the root, have a "#seq" key.
  95. - Comments, directives, and process instructions are unmarshalled into the Map using the
  96. keys "#comment", "#directive", and "#procinst", respectively. (See documentation for more
  97. specifics.)
  98. - Name space syntax is preserved:
  99. - <ns:key>something</ns.key> parses to map["ns:key"]interface{}{"something"}
  100. - xmlns:ns="http://myns.com/ns" parses to map["xmlns:ns"]interface{}{"http://myns.com/ns"}
  101. Both
  102. - By default, "Nan", "Inf", and "-Inf" values are not cast to float64. If you want them
  103. to be cast, set a flag to cast them using CastNanInf(true).
  104. XML ENCODING CONVENTIONS
  105. - 'nil' Map values, which may represent 'null' JSON values, are encoded as "<tag/>".
  106. NOTE: the operation is not symmetric as "<tag/>" elements are decoded as 'tag:""' Map values,
  107. which, then, encode in JSON as '"tag":""' values..
  108. - ALSO: there is no guarantee that the encoded XML doc will be the same as the decoded one. (Go
  109. randomizes the walk through map[string]interface{} values.) If you plan to re-encode the
  110. Map value to XML and want the same sequencing of elements look at NewMapXmlSeq() and
  111. mv.XmlSeq() - these try to preserve the element sequencing but with added complexity when
  112. working with the Map representation.
  113. */
  114. package mxj