114 lines
2.3 KiB
Go
114 lines
2.3 KiB
Go
// Package serialize ...
|
|
//
|
|
// Description : serialize ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2024-10-23 17:51
|
|
package serialize
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/xml"
|
|
"io"
|
|
)
|
|
|
|
var (
|
|
Xml = &ownXml{}
|
|
)
|
|
|
|
type ownXml struct{}
|
|
|
|
func (o *ownXml) UnmarshalWithNumber(byteData []byte, receiver any) error {
|
|
return xml.NewDecoder(bytes.NewReader(byteData)).Decode(receiver)
|
|
}
|
|
|
|
func (o *ownXml) UnmarshalWithNumberIgnoreError(byteData []byte, receiver any) {
|
|
_ = o.UnmarshalWithNumber(byteData, receiver)
|
|
return
|
|
}
|
|
|
|
func (o *ownXml) UnmarshalWithNumberForIOReader(ioReader io.ReadCloser, receiver any) error {
|
|
return xml.NewDecoder(ioReader).Decode(receiver)
|
|
}
|
|
|
|
func (o *ownXml) UnmarshalWithNumberForIOReaderIgnoreError(ioReader io.ReadCloser, receiver any) {
|
|
_ = o.UnmarshalWithNumberForIOReader(ioReader, receiver)
|
|
return
|
|
}
|
|
|
|
func (o *ownXml) UnmarshalWithNumberForString(input string, receiver any) error {
|
|
return o.UnmarshalWithNumber([]byte(input), receiver)
|
|
}
|
|
|
|
func (o *ownXml) UnmarshalWithNumberForStringIgnoreError(input string, receiver any) {
|
|
_ = o.UnmarshalWithNumberForString(input, receiver)
|
|
return
|
|
}
|
|
|
|
func (o *ownXml) MarshalForByte(input any) ([]byte, error) {
|
|
return xml.Marshal(input)
|
|
}
|
|
|
|
func (o *ownXml) MarshalForByteIgnoreError(input any) []byte {
|
|
byteData, _ := o.MarshalForByte(input)
|
|
return byteData
|
|
}
|
|
|
|
func (o *ownXml) MarshalForString(input any) (string, error) {
|
|
byteData, err := o.MarshalForByte(input)
|
|
if nil != err {
|
|
return "", err
|
|
}
|
|
return string(byteData), nil
|
|
}
|
|
|
|
func (o *ownXml) MarshalForStringIgnoreError(input any) string {
|
|
str, _ := o.MarshalForString(input)
|
|
return str
|
|
}
|
|
|
|
type XmlStringMap map[string]string
|
|
|
|
type xmlMapEntry struct {
|
|
XMLName xml.Name
|
|
Value string `xml:",chardata"`
|
|
}
|
|
|
|
func (m *XmlStringMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
|
if nil == m {
|
|
return nil
|
|
}
|
|
if len(*m) == 0 {
|
|
return nil
|
|
}
|
|
|
|
err := e.EncodeToken(start)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
for k, v := range *m {
|
|
_ = e.Encode(xmlMapEntry{XMLName: xml.Name{Local: k}, Value: v})
|
|
}
|
|
|
|
return e.EncodeToken(start.End())
|
|
}
|
|
|
|
func (m *XmlStringMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
|
|
*m = XmlStringMap{}
|
|
for {
|
|
var e xmlMapEntry
|
|
|
|
err := d.Decode(&e)
|
|
if err == io.EOF {
|
|
break
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
|
|
(*m)[e.XMLName.Local] = e.Value
|
|
}
|
|
return nil
|
|
}
|