diff --git a/isvalid_test.go b/isvalid_test.go new file mode 100644 index 0000000..d61841c --- /dev/null +++ b/isvalid_test.go @@ -0,0 +1,37 @@ +package mxj + +import ( + "fmt" + "testing" +) + +func TestXmlCheckIsValid(t *testing.T) { + fmt.Println("================== TestXmlCheckIsValid") + + data := []byte(`{"":"empty", "$invalid":"hex$", "entities":"<>&", "nil": null}`) + m, err := NewMapJson(data) + if err != nil { + t.Fatal("NewMapJson err;", err) + } + fmt.Printf("%v\n", m) + + XmlCheckIsValid() + defer XmlCheckIsValid() + if _, err = m.Xml(); err == nil { + t.Fatal("Xml err: nil") + } + + if _, err = m.XmlIndent("", " "); err == nil { + t.Fatal("XmlIndent err: nil") + } + + ms, err := NewMapXmlSeq([]byte(`element`)) + fmt.Printf("%v\n", ms) + if _, err = ms.Xml(); err != nil { + t.Fatal("Xml err:", err) + } + + if _, err = ms.XmlIndent("", " "); err != nil { + t.Fatal("XmlIndent err:", err) + } +} diff --git a/xml.go b/xml.go index a551186..04788fd 100644 --- a/xml.go +++ b/xml.go @@ -694,8 +694,15 @@ func (mv Map) Xml(rootTag ...string) ([]byte, error) { } done: if xmlCheckIsValid { - if _, err = NewMapXml(b.Bytes()); err != nil { - return nil, err + d := xml.NewDecoder(bytes.NewReader(b.Bytes())) + for _, err = d.Token(); err != io.EOF; { + _, err = d.Token() + if err == io.EOF { + err = nil + break + } else if err != nil { + return nil, err + } } } return b.Bytes(), err @@ -937,8 +944,15 @@ func (mv Map) XmlIndent(prefix, indent string, rootTag ...string) ([]byte, error err = marshalMapToXmlIndent(true, b, DefaultRootTag, m, p) } if xmlCheckIsValid { - if _, err = NewMapXml(b.Bytes()); err != nil { - return nil, err + d := xml.NewDecoder(bytes.NewReader(b.Bytes())) + for _, err = d.Token(); err != io.EOF; { + _, err = d.Token() + if err == io.EOF { + err = nil + break + } else if err != nil { + return nil, err + } } } return b.Bytes(), err diff --git a/xmlseq.go b/xmlseq.go index 6427d0f..3fb90b8 100644 --- a/xmlseq.go +++ b/xmlseq.go @@ -448,8 +448,15 @@ func (mv MapSeq) Xml(rootTag ...string) ([]byte, error) { } done: if xmlCheckIsValid { - if _, err = NewMapXml([]byte(*s)); err != nil { - return nil, err + d := xml.NewDecoder(bytes.NewReader([]byte(*s))) + for _, err = d.Token(); err != io.EOF; { + _, err = d.Token() + if err == io.EOF { + err = nil + break + } else if err != nil { + return nil, err + } } } return []byte(*s), err @@ -544,6 +551,16 @@ func (mv MapSeq) XmlIndent(prefix, indent string, rootTag ...string) ([]byte, er if _, err = NewMapXml([]byte(*s)); err != nil { return nil, err } + d := xml.NewDecoder(bytes.NewReader([]byte(*s))) + for _, err = d.Token(); err != io.EOF; { + _, err = d.Token() + if err == io.EOF { + err = nil + break + } else if err != nil { + return nil, err + } + } } return []byte(*s), err }