github.com/zhongdalu/gf@v1.0.0/g/encoding/gxml/gxml.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  // Package gxml provides accessing and converting for XML content.
     8  package gxml
     9  
    10  import (
    11  	"fmt"
    12  	"github.com/zhongdalu/gf/g/encoding/gcharset"
    13  	"github.com/zhongdalu/gf/g/text/gregex"
    14  	"github.com/zhongdalu/gf/third/github.com/clbanning/mxj"
    15  	"strings"
    16  )
    17  
    18  // 将XML内容解析为map变量
    19  func Decode(content []byte) (map[string]interface{}, error) {
    20  	res, err := convert(content)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	return mxj.NewMapXml(res)
    25  }
    26  
    27  // 将map变量解析为XML格式内容
    28  func Encode(v map[string]interface{}, rootTag ...string) ([]byte, error) {
    29  	return mxj.Map(v).Xml(rootTag...)
    30  }
    31  
    32  func EncodeWithIndent(v map[string]interface{}, rootTag ...string) ([]byte, error) {
    33  	return mxj.Map(v).XmlIndent("", "\t", rootTag...)
    34  }
    35  
    36  // XML格式内容直接转换为JSON格式内容
    37  func ToJson(content []byte) ([]byte, error) {
    38  	res, err := convert(content)
    39  	if err != nil {
    40  		fmt.Println("convert error. ", err)
    41  		return nil, err
    42  	}
    43  
    44  	mv, err := mxj.NewMapXml(res)
    45  	if err == nil {
    46  		return mv.Json()
    47  	} else {
    48  		return nil, err
    49  	}
    50  }
    51  
    52  // XML字符集预处理
    53  func convert(xml []byte) (res []byte, err error) {
    54  	patten := `<\?xml.*encoding\s*=\s*['|"](.*?)['|"].*\?>`
    55  	matchStr, err := gregex.MatchString(patten, string(xml))
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	xmlEncode := "UTF-8"
    60  	if len(matchStr) == 2 {
    61  		xmlEncode = matchStr[1]
    62  	}
    63  	xmlEncode = strings.ToUpper(xmlEncode)
    64  	res, err = gregex.Replace(patten, []byte(""), xml)
    65  	if err != nil {
    66  		return nil, err
    67  	}
    68  	if xmlEncode != "UTF-8" && xmlEncode != "UTF8" {
    69  		dst, err := gcharset.Convert("UTF-8", xmlEncode, string(res))
    70  		if err != nil {
    71  			return nil, err
    72  		}
    73  		res = []byte(dst)
    74  	}
    75  	return res, nil
    76  }