...

Source file src/github.com/clbanning/mxj/v2/x2j-wrapper/reader2j.go

Documentation: github.com/clbanning/mxj/v2/x2j-wrapper

     1  // Copyright 2012-2018 Charles Banning. 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  // io.Reader --> map[string]interface{} or JSON string
     5  // nothing magic - just implements generic Go case
     6  
     7  package x2j
     8  
     9  import (
    10  	"encoding/json"
    11  	"io"
    12  
    13  	"github.com/clbanning/mxj"
    14  )
    15  
    16  // ToMap() - parse a XML io.Reader to a map[string]interface{}
    17  func ToMap(rdr io.Reader, recast ...bool) (map[string]interface{}, error) {
    18  	var r bool
    19  	if len(recast) == 1 {
    20  		r = recast[0]
    21  	}
    22  	return mxj.NewMapXmlReader(rdr, r)
    23  }
    24  
    25  // ToJson() - parse a XML io.Reader to a JSON string
    26  func ToJson(rdr io.Reader, recast ...bool) (string, error) {
    27  	var r bool
    28  	if len(recast) == 1 {
    29  		r = recast[0]
    30  	}
    31  	m, merr := mxj.NewMapXmlReader(rdr, r)
    32  	if m == nil || merr != nil {
    33  		return "", merr
    34  	}
    35  
    36  	b, berr := json.Marshal(m)
    37  	if berr != nil {
    38  		return "", berr
    39  	}
    40  
    41  	return string(b), nil
    42  }
    43  
    44  // ToJsonIndent - the pretty form of ReaderToJson
    45  func ToJsonIndent(rdr io.Reader, recast ...bool) (string, error) {
    46  	var r bool
    47  	if len(recast) == 1 {
    48  		r = recast[0]
    49  	}
    50  	m, merr := mxj.NewMapXmlReader(rdr, r)
    51  	if m == nil || merr != nil {
    52  		return "", merr
    53  	}
    54  
    55  	b, berr := json.MarshalIndent(m, "", "  ")
    56  	if berr != nil {
    57  		return "", berr
    58  	}
    59  
    60  	// NOTE: don't have to worry about safe JSON marshaling with json.Marshal, since '<' and '>" are reservedin XML.
    61  	return string(b), nil
    62  }
    63  
    64  // ReaderValuesFromTagPath - io.Reader version of ValuesFromTagPath()
    65  func ReaderValuesFromTagPath(rdr io.Reader, path string, getAttrs ...bool) ([]interface{}, error) {
    66  	var a bool
    67  	if len(getAttrs) == 1 {
    68  		a = getAttrs[0]
    69  	}
    70  	m, err := mxj.NewMapXmlReader(rdr)
    71  	if err != nil {
    72  		return nil, err
    73  	}
    74  
    75  	return ValuesFromKeyPath(m, path, a), nil
    76  }
    77  
    78  // ReaderValuesForTag - io.Reader version of ValuesForTag()
    79  func ReaderValuesForTag(rdr io.Reader, tag string) ([]interface{}, error) {
    80  	m, err := mxj.NewMapXmlReader(rdr)
    81  	if err != nil {
    82  		return nil, err
    83  	}
    84  
    85  	return ValuesForKey(m, tag), nil
    86  }
    87  

View as plain text