xml2json

package module
v0.0.0-...-567798c Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2023 License: MIT Imports: 10 Imported by: 0

README

goxml2json CircleCI

Go package that converts XML to JSON

Install
go get -u https://github.com/integration-system/goxml2json
Importing
import https://github.com/integration-system/goxml2json
Usage

Code example

  package main

import (
	"fmt"
	"strings"

	xj "github.com/basgys/goxml2json"
)

func main() {
	// xml is an io.Reader
	xml := strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><hello>world</hello>`)
	converter := xj.NewConverter(
		xj.WithAttrPrefix("-"),
	)
	json, err := converter.Convert(xml)
	if err != nil {
		panic("That's embarrassing...")
	}

	fmt.Println(json.String())
	// {"hello": ["world"]}
}

Input

  <?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="CGImap 0.0.2">
    <bounds minlat="54.0889580" minlon="12.2487570" maxlat="54.0913900" maxlon="12.2524800"/>
    <foo>bar</foo>
</osm>

Output

  {
  "osm": {
    "-version": 0.6,
    "-generator": "CGImap 0.0.2",
    "bounds": {
      "-minlat": "54.0889580",
      "-minlon": "12.2487570",
      "-maxlat": "54.0913900",
      "-maxlon": "12.2524800"
    },
    "foo": "bar"
  }
}

With type conversion

  package main

import (
	"fmt"
	"strings"

	xj "github.com/basgys/goxml2json"
)

func main() {
	// xml is an io.Reader
	xml := strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?><price>19.95</price>`)
	converter := xj.NewConverter(
		xj.WithAttrPrefix("-"),
		xj.WithTypeConverter(xj.Float),
	)
	json, err := converter.Convert(xml)
	if err != nil {
		panic("That's embarrassing...")
	}

	fmt.Println(json.String())
	// {"price": [19.95]}
}

Documentation

Overview

Package xml2json is an XML to JSON converter

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TrimNonGraphic

func TrimNonGraphic(s string) string

TrimNonGraphic returns a slice of the string s, with all leading and trailing non graphic characters and spaces removed.

Graphic characters include letters, marks, numbers, punctuation, symbols, and spaces, from categories L, M, N, P, S, Zs. Spacing characters are set by category Z and property Pattern_White_Space.

Types

type Converter

type Converter struct {
	// contains filtered or unexported fields
}

func NewConverter

func NewConverter(plugins ...Plugin) Converter

func (Converter) Convert

func (s Converter) Convert(r io.Reader) (*bytes.Buffer, error)

Convert converts the given XML document to JSON

type Decoder

type Decoder struct {
	// contains filtered or unexported fields
}

A Decoder reads and decodes XML objects from an input stream.

func NewDecoder

func NewDecoder(reader io.Reader, plugins ...Plugin) *Decoder

NewDecoder returns a new decoder that reads from reader.

func (*Decoder) Decode

func (dec *Decoder) Decode(root *Node) error

Decode reads the next JSON-encoded value from its input and stores it in the value pointed to by v.

func (*Decoder) DecodeWithCustomPrefixes

func (dec *Decoder) DecodeWithCustomPrefixes(root *Node, contentPrefix string, attributePrefix string) error

func (*Decoder) ExcludeAttributes

func (dec *Decoder) ExcludeAttributes(attrs []string)

func (*Decoder) SetAttributePrefix

func (dec *Decoder) SetAttributePrefix(prefix string)

func (*Decoder) SetContentPrefix

func (dec *Decoder) SetContentPrefix(prefix string)

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

An Encoder writes JSON objects to an output stream.

func NewEncoder

func NewEncoder(writer io.Writer, plugins ...Plugin) *Encoder

NewEncoder returns a new encoder that writes to writer.

func (*Encoder) Encode

func (enc *Encoder) Encode(root *Node) error

Encode writes the JSON encoding of v to the stream

type JSType

type JSType int

https://cswr.github.io/JsonSchema/spec/basic_types/ JSType is a JavaScript extracted from a string

const (
	Bool JSType = iota
	Int
	Float
	String
	Null
)

func Str2JSType

func Str2JSType(s string) JSType

Str2JSType extract a JavaScript type from a string

type Node

type Node struct {
	Label    string
	Children map[string]Nodes
	Data     string
}

Node is a data element on a tree

func (*Node) AddChild

func (n *Node) AddChild(s string, c *Node)

AddChild appends a node to the list of children

func (*Node) GetChild

func (n *Node) GetChild(path string) *Node

GetChild returns child by path if exists. Path looks like "grandparent.parent.child.grandchild"

func (*Node) IsComplex

func (n *Node) IsComplex() bool

IsComplex returns whether it is a complex type (has children)

type Nodes

type Nodes []*Node

Nodes is a list of nodes

type Plugin

type Plugin interface {
	AddToEncoder(*Encoder) *Encoder
	AddToDecoder(*Decoder) *Decoder
}

Plugin is added to an encoder or/and to an decoder to allow custom functionality at runtime

func AllAttrToArray

func AllAttrToArray() Plugin

func AttrToArray

func AttrToArray(attrList ...string) Plugin

func ExcludeAttributes

func ExcludeAttributes(attrs ...string) Plugin

ExcludeAttributes excludes some xml attributes, for example, xmlns:xsi, xsi:noNamespaceSchemaLocation

func WithAttrPrefix

func WithAttrPrefix(prefix string) Plugin

WithAttrPrefix appends the given prefix to the json output of xml attribute fields to preserve namespaces

func WithContentPrefix

func WithContentPrefix(prefix string) Plugin

WithContentPrefix appends the given prefix to the json output of xml content fields to preserve namespaces

func WithTypeConverter

func WithTypeConverter(ts ...JSType) Plugin

WithTypeConverter allows customized js type conversion behavior by passing in the desired JSTypes

Jump to

Keyboard shortcuts

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