Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修改了 xmltomap 方法的 bug #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 43 additions & 23 deletions util.go
Original file line number Diff line number Diff line change
@@ -1,42 +1,62 @@
package wxpay

import (
"bytes"
"crypto/tls"
"encoding/pem"
"encoding/xml"
"golang.org/x/crypto/pkcs12"
"log"
"strconv"
"strings"
"time"
"io"
"bytes"
)

func XmlToMap(xmlStr string) Params {
type xmlMapEntry struct {
XMLName xml.Name
Value string `xml:",chardata"`
}

params := make(Params)
decoder := xml.NewDecoder(strings.NewReader(xmlStr))

var (
key string
value string
)

for t, err := decoder.Token(); err == nil; t, err = decoder.Token() {
switch token := t.(type) {
case xml.StartElement: // 开始标签
key = token.Name.Local
case xml.CharData: // 标签内容
content := string([]byte(token))
value = content
}
if key != "xml" {
if value != "\n" {
params.SetString(key, value)
}
func (m Params) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
if len(m) == 0 {
return nil
}
start.Name.Local = "xml" // 更改xml开始标签
err := e.EncodeToken(start)
if err != nil {
return err
}

for k, v := range m {
e.Encode(xmlMapEntry{XMLName: xml.Name{Local: k}, Value: v})
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for k, v := range m {
err := e.Encode(xmlMapEntry{XMLName: xml.Name{Local: k}, Value: v})
if err != nil {
return err
break
}

}

return e.EncodeToken(start.End())
}

func (m *Params) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
*m = Params{}
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
}

func XmlToMap(xmlStr string) Params {
params := make(Params)
err := xml.Unmarshal([]byte(xmlStr), &params)
if err != nil {
panic(err)
}
return params
}

Expand Down