...

Source file src/github.com/clbanning/mxj/v2/examples/gonuts1a.go

Documentation: github.com/clbanning/mxj/v2/examples

     1  // https://groups.google.com/forum/#!searchin/golang-nuts/idnet$20netid/golang-nuts/guM3ZHHqSF0/K1pBpMqQSSwJ
     2  // http://play.golang.org/p/BFFDxphKYK
     3  
     4  package main
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"github.com/clbanning/mxj"
    10  	"io"
    11  )
    12  
    13  // Demo how to re-label a key using mv.NewMap().
    14  // Need to normalize from an XML stream the tags "netid" and "idnet".
    15  // Solution: make everything "netid".
    16  
    17  var msg1 = []byte(`
    18  <?xml version="1.0" encoding="UTF-8"?>
    19  <data>
    20      <netid>
    21          <disable>no</disable>
    22          <text1>default:text</text1>
    23          <word1>default:word</word1>
    24      </netid>
    25  </data>
    26  `)
    27  
    28  var msg2 = []byte(`
    29  <?xml version="1.0" encoding="UTF-8"?>
    30  <data>
    31      <idnet>
    32          <disable>yes</disable>
    33          <text1>default:text</text1>
    34          <word1>default:word</word1>
    35      </idnet>
    36  </data>
    37  `)
    38  
    39  func main() {
    40  	// let's create a message stream
    41  	buf := new(bytes.Buffer)
    42  	// load a couple of messages into it
    43  	_, _ = buf.Write(msg1)
    44  	_, _ = buf.Write(msg2)
    45  
    46  	n := 0
    47  	for {
    48  		n++
    49  		// read the stream as Map values - quit on io.EOF
    50  		m, raw, merr := mxj.NewMapXmlReaderRaw(buf)
    51  		if merr != nil && merr != io.EOF {
    52  			// handle error - for demo we just print it and continue
    53  			fmt.Printf("msg: %d - merr: %s\n", n, merr.Error())
    54  			continue
    55  		} else if merr == io.EOF {
    56  			break
    57  		}
    58  
    59  		// the first keypair retains values if data correct
    60  		// the second keypair relabels "idnet" to "netid"
    61  		n, _ := m.NewMap("data.netid", "data.idnet:data.netid")
    62  		x, _ := n.XmlIndent("", "  ")
    63  
    64  		fmt.Println("original value:", string(raw))
    65  		fmt.Println("new value:")
    66  		fmt.Println(string(x))
    67  	}
    68  }
    69  

View as plain text