func main() { inputReader := strings.NewReader(input) decoder := xml.NewDecoder(inputReader) for { // Read tokens from the XML document in a stream. t, _ := decoder.Token() if t == nil { break } // Inspect the type of the token just read. //fmt.Printf("\n<!--%#v-->\n", t) switch x := t.(type) { case xml.StartElement: fmt.Printf("<%s", x.Name.Local) for _, attr := range x.Attr { fmt.Printf(" %s=\"", attr.Name.Local) xml.EscapeText(os.Stdout, []byte(attr.Value)) os.Stdout.Write([]byte{'"'}) } fmt.Printf(">") case xml.CharData: xml.EscapeText(os.Stdout, bytes.TrimSpace(x)) case xml.EndElement: fmt.Printf("</%s>\n", x.Name.Local) } } }
func value_to_xml(v interface{}) (string, error) { switch t := v.(type) { case int, int8, int64, int32, *int, *int8, *int64, *int32: return fmt.Sprintf("<int>%d</int>", t), nil case string: buf := bytes.NewBuffer(make([]byte, 0)) err := xml.EscapeText(buf, []byte(t)) if err != nil { return "", err } return fmt.Sprintf("<string>%s</string>", buf.String()), nil case []byte: return fmt.Sprintf("<base64>%s</base64>", base64.StdEncoding.EncodeToString(t)), nil case float32, float64, *float32, *float64: return fmt.Sprintf("<double>%f</double>", t), nil case bool: return fmt.Sprintf("<boolean>%d</boolean>", btoi(t)), nil case time.Time: buf := bytes.NewBuffer(make([]byte, 0)) err := xml.EscapeText(buf, []byte(t.Format(time_ISO8601_FORMAT))) if err != nil { return "", err } return fmt.Sprintf("<dateTime.iso8601>%s</dateTime.iso8601>", buf.String()), nil case *time.Time: buf := bytes.NewBuffer(make([]byte, 0)) err := xml.EscapeText(buf, []byte(t.Format(time_ISO8601_FORMAT))) if err != nil { return "", err } return fmt.Sprintf("<dateTime.iso8601>%s</dateTime.iso8601>", buf.String()), nil case []interface{}: tmp_str_arr := []string{"<array><data>"} for _, v := range t { subval, err := value_to_xml(v) if err != nil { return "", err } tmp_str_arr = append(tmp_str_arr, fmt.Sprintf("<value>%s</value>", subval)) } tmp_str_arr = append(tmp_str_arr, "</data></array>") return strings.Join(tmp_str_arr, ""), nil case map[string]interface{}: tmp_str_arr := []string{"<struct>"} for name, item := range t { tmp_str_arr = append(tmp_str_arr, "<member>") tmp_str_arr = append(tmp_str_arr, fmt.Sprintf("<name>%s</name>", name)) subval, err := value_to_xml(item) if err != nil { return "", err } tmp_str_arr = append(tmp_str_arr, fmt.Sprintf("<value>%s</value>", subval)) tmp_str_arr = append(tmp_str_arr, "</member>") } tmp_str_arr = append(tmp_str_arr, "</struct>") return strings.Join(tmp_str_arr, ""), nil default: return "", errors.New("Unrecognized type") } }
func encodeDomainCheck(buf *bytes.Buffer, domains []string, extFee bool) error { buf.Reset() buf.WriteString(xmlCommandPrefix) buf.WriteString(`<check>`) buf.WriteString(`<domain:check xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">`) for _, domain := range domains { buf.WriteString(`<domain:name>`) xml.EscapeText(buf, []byte(domain)) buf.WriteString(`</domain:name>`) } buf.WriteString(`</domain:check>`) buf.WriteString(`</check>`) if extFee { // Extensions buf.WriteString(`<extension>`) // CentralNic fee extension buf.WriteString(`<fee:check xmlns:fee="urn:ietf:params:xml:ns:fee-0.5">`) for _, domain := range domains { buf.WriteString(`<fee:domain>`) buf.WriteString(`<fee:name>`) xml.EscapeText(buf, []byte(domain)) buf.WriteString(`</fee:name>`) buf.WriteString(`<fee:command>create</fee:command>`) buf.WriteString(`</fee:domain>`) } buf.WriteString(`</fee:check>`) buf.WriteString(`</extension>`) } buf.WriteString(xmlCommandSuffix) return nil }
// meh3 func genQuery(query string, args dict) []byte { var out bytes.Buffer out.WriteString("<query") for key, val := range args { fmt.Fprintf(&out, " %s=\"", key) xml.EscapeText(&out, []byte(val)) out.WriteString("\"") } out.WriteString(">") xml.EscapeText(&out, []byte(query)) out.WriteString("</query>\r\n.\r\n") return out.Bytes() }
// ToXML marshal map[string]string to xmlWriter with xml format, the root node name is xml. // NOTE: This function assumes the key of m map[string]string are legitimate xml name string // that does not contain the required escape character! func (x *Xml) ToXML(xmlWriter io.Writer, m map[string]string) (err error) { if xmlWriter == nil { return errors.New("nil xmlWriter") } if _, err = io.WriteString(xmlWriter, "<xml>"); err != nil { return } for k, v := range m { if _, err = io.WriteString(xmlWriter, "<"+k+">"); err != nil { return } if err = xml.EscapeText(xmlWriter, []byte(v)); err != nil { return } if _, err = io.WriteString(xmlWriter, "</"+k+">"); err != nil { return } } if _, err = io.WriteString(xmlWriter, "</xml>"); err != nil { return } return }
func (w *Writer) WriteQuad(q quad.Quad) error { if w.err != nil { return w.err } if !w.written { if _, err := w.w.Write([]byte(header)); err != nil { return err } w.written = true w.nodes = make(map[string]int) } s := w.writeNode(quad.StringOf(q.Subject)) o := w.writeNode(quad.StringOf(q.Object)) if w.err != nil { return w.err } _, w.err = fmt.Fprintf(w.w, "\t\t<edge source=\"n%d\" target=\"n%d\"><data key=\"d1\">", s, o) if w.err != nil { return w.err } if w.err = xml.EscapeText(w.w, []byte(quad.StringOf(q.Predicate))); w.err != nil { return w.err } _, w.err = w.w.Write([]byte("</data></edge>\n")) return w.err }
// Return an XML-RPC fault func writeFault(out io.Writer, code int, msg string) { fmt.Fprintf(out, `<?xml version="1.0"?> <methodResponse> <fault> <value> <struct> <member> <name>faultCode</name> <value><int>%d</int></value> </member> <member> <name>faultString</name> <value>`, code) err := xml.EscapeText(out, []byte(msg)) fmt.Fprintf(out, `</value> </member> </struct> </value> </fault> </methodResponse>`) // XXX dump the error to Stderr for now if err != nil { fmt.Fprintf(os.Stderr, "Cannot write fault#%d(%s): %v\n", code, msg, err) } }
// The HTTP voice processing endpoint reads DTMF (input from Twilio request) and translates it into a statement and execute. func (sh *WebShell) httpAPIVoiceMessage(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/xml") w.Header().Set("Cache-Control", "must-revalidate") w.WriteHeader(http.StatusOK) digits := r.FormValue("Digits") decodedLetters := voiceDecodeDTMF(digits) log.Printf("Voice message got digits: %s (decoded - %s)", digits, decodedLetters) if cmd := sh.cmdFind(decodedLetters); cmd == "" { // PIN mismatch w.Write([]byte(`<?xml version="1.0" encoding="UTF-8"?> <Response> <Say>Sorry</Say> <Hangup/> </Response> `)) } else { // Speak the command result and repeat output := sh.cmdRun(cmd, sh.WebTimeoutSec, sh.WebTruncateLen, true, true) var escapeOutput bytes.Buffer if err := xml.EscapeText(&escapeOutput, []byte(output)); err != nil { log.Printf("XML escape failed - %v", err) } w.Write([]byte(fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?> <Response> <Gather action="%s%s" method="POST" timeout="15" finishOnKey="#" numDigits="1000"> <Say voice="man" loop="1" language="en">%s over</Say> </Gather> </Response> `, sh.VoiceEndpointPrefix, sh.VoiceProcEndpoint, escapeOutput.String()))) } }
func serializeItem(k string, v interface{}, w io.Writer) { w.Write([]byte(`<item key="`)) xml.EscapeText(w, []byte(k)) w.Write([]byte(`">`)) switch i := v.(type) { case string: xml.EscapeText(w, []byte(i)) case NestedStringMap: serializeMap(i, w) case []NestedStringMap: serializeNSMArray(i, w) case []string: serializeStringArray(i, w) } w.Write([]byte(`</item>`)) }
func (s *Shell) NewCommand(cmd string, arguments []string) (string, error) { var buf = bytes.NewBuffer(make([]byte, 0, len(cmd))) if e := xml.EscapeText(buf, []byte(cmd)); nil != e { return "", e } env := &envelope.CreateCommand{Uuid(), s.Id, strings.Replace(buf.String(), """, """, -1), arguments} reader, err := s.Deliver(bytes.NewBufferString(env.Xml())) if err != nil { return "", err } defer closeReader(reader) decoder := xml.NewDecoder(reader) if err := ReadEnvelopeBody(decoder); nil != err { return "", err } ok, err := locateElements(decoder, []string{"CommandResponse", "CommandId"}) if nil != err { return "", errors.New("locate 'Envelope/Body/CommandResponse/CommandId' failed, " + err.Error()) } if !ok { return "", ElementNotExists("Envelope/Body/CommandResponse/CommandId") } id, e := readXmlText(decoder) if nil != e { return "", errors.New("read CommandId from the response failed, " + e.Error()) } return id, nil }
// 格式化 map[string]string 为 xml 格式 // 用于微信支付 func FormatMapToXML(xmlWriter io.Writer, Map map[string]string) (err error) { if xmlWriter == nil { return errors.New("xmlWriter == nil") } _, err = io.WriteString(xmlWriter, "<xml>\n") if err != nil { return } for key, value := range Map { _, err = io.WriteString(xmlWriter, "<"+key+">") if err != nil { return } if err = xml.EscapeText(xmlWriter, []byte(value)); err != nil { return } _, err = io.WriteString(xmlWriter, "</"+key+">\n") if err != nil { return } } _, err = io.WriteString(xmlWriter, "</xml>") if err != nil { return } return }
func escapeXml(in string) string { var out bytes.Buffer err := xml.EscapeText(&out, []byte(in)) if err != nil { panic("Could not escape XML: " + err.Error()) } return out.String() }
func (this *Node) printText() []byte { val := []byte(this.Value) if len(this.Parent.Children) > 1 { return val } var b bytes.Buffer xml.EscapeText(&b, val) return b.Bytes() }
func escapeXml(s string) string { buf := new(bytes.Buffer) buf.Grow(len(s)) err := xml.EscapeText(buf, []byte(s)) if err != nil { panic(err) } return buf.String() }
func escapeXmlText(s string) (string, error) { buffer := new(bytes.Buffer) err := xml.EscapeText(buffer, []byte(s)) if err != nil { return "", err } return buffer.String(), nil }
// encodeRequestAction is a hacky way to create an encoded SOAP envelope // containing the given action. Experiments with one router have shown that it // 500s for requests where the outer default xmlns is set to the SOAP // namespace, and then reassigning the default namespace within that to the // service namespace. Hand-coding the outer XML to work-around this. func encodeRequestAction(actionNamespace, actionName string, inAction interface{}) ([]byte, error) { requestBuf := new(bytes.Buffer) requestBuf.WriteString(soapPrefix) requestBuf.WriteString(`<u:`) xml.EscapeText(requestBuf, []byte(actionName)) requestBuf.WriteString(` xmlns:u="`) xml.EscapeText(requestBuf, []byte(actionNamespace)) requestBuf.WriteString(`">`) if inAction != nil { if err := encodeRequestArgs(requestBuf, inAction); err != nil { return nil, err } } requestBuf.WriteString(`</u:`) xml.EscapeText(requestBuf, []byte(actionName)) requestBuf.WriteString(`>`) requestBuf.WriteString(soapSuffix) return requestBuf.Bytes(), nil }
func (p Post) Excerpt() string { r := regexp.MustCompile("<p>(.+?)</p>") result := r.FindStringSubmatch(p.htmlContent) if len(result) > 1 { buf := new(bytes.Buffer) xml.EscapeText(buf, []byte(result[1])) return buf.String() + " ..." } return "" }
// Connect connects and logs in to a vSphere host. func Connect(host, user, pwd string) (*Vsphere, error) { header := http.Header{ "Content-Type": []string{`text/xml; charset=UTF-8`}, "SOAPAction": []string{`"urn:vim25/5.5"`}, } jar, err := cookiejar.New(nil) if err != nil { return nil, err } v := &Vsphere{ url: &url.URL{ Scheme: "https", Host: host, Path: "/sdk", }, header: header, client: &http.Client{ Timeout: time.Minute, Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, }, }, cookies: jar, } uuid := struct { UUID string `xml:"Body>RetrieveServiceContentResponse>returnval>about>instanceUuid"` }{} if err := v.call(soapConnect, &uuid); err != nil { return nil, err } if uuid.UUID == "" { return nil, fmt.Errorf("vsphere: no UUID during connect") } userbuf := new(bytes.Buffer) pwdbuf := new(bytes.Buffer) xml.EscapeText(userbuf, []byte(user)) xml.EscapeText(pwdbuf, []byte(pwd)) if err := v.call(fmt.Sprintf(soapLogin, userbuf, pwdbuf), nil); err != nil { return nil, err } return v, nil }
func escape(s string) string { for i := 0; i < len(s); i++ { switch s[i] { case '"', '&', '\'', '<', '>': b := bytes.NewBuffer(nil) xml.EscapeText(b, []byte(s)) return b.String() } } return s }
func (res *Resources) SetColor(name, value string) *Resources { for index, _ := range res.Colors { if name == res.Colors[index].Name { m := new(bytes.Buffer) xml.EscapeText(m, []byte(value)) res.Colors[index].Value = m.String() break } } return res }
func transformContainer(o *bytes.Buffer, cont *namedContainer) error { var printName string if cont.name != "" { escapedNameBuf := bytes.NewBuffer(nil) err := xml.EscapeText(escapedNameBuf, []byte(cont.name)) if err != nil { return err } printName = fmt.Sprintf(" name=\"%s\"", escapedNameBuf.String()) } data := cont.Data() switch data.(type) { case nil: o.WriteString(fmt.Sprintf("<json:null%s />", printName)) case bool: o.WriteString(fmt.Sprintf("<json:boolean%s>%t</json:boolean>", printName, data)) case json.Number: o.WriteString(fmt.Sprintf("<json:number%s>%v</json:number>", printName, data)) case string: o.WriteString(fmt.Sprintf("<json:string%s>%v</json:string>", printName, data)) case []interface{}: o.WriteString(fmt.Sprintf("<json:array%s>", printName)) arrayChildren, err := cont.Children() if err != nil { return err } for _, child := range arrayChildren { if err := transformContainer(o, &namedContainer{Container: child}); err != nil { return err } } o.WriteString("</json:array>") case map[string]interface{}: o.WriteString(fmt.Sprintf("<json:object%s>", printName)) if err := sortAndTransformObject(o, cont); err != nil { return err } o.WriteString("</json:object>") } return nil }
func (xf xfdf) WriteTo(w io.Writer) (int64, error) { cew := &countErrWriter{w: w} if _, err := io.WriteString(cew, `<?xml version="1.0" encoding="UTF-8"?> <xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve"> <fields> `); err != nil { return cew.n, err } for _, key := range xf.Fields { io.WriteString(cew, ` <field name="`) cew.err = xml.EscapeText(cew, []byte(key)) io.WriteString(cew, `"><value>`) cew.err = xml.EscapeText(cew, []byte("")) io.WriteString(cew, "</value></field>\n") if cew.err != nil { return cew.n, cew.err } } io.WriteString(cew, ` </fields> </xfdf>`) return cew.n, cew.err }
func xml_addrs(w http.ResponseWriter, r *http.Request) { if !ipchecker(r) { return } w.Header()["Content-Type"] = []string{"text/xml"} w.Write([]byte("<addrbook>")) // Address Book book := wallet.LoadWalfile(common.GocoinHomeDir+"wallet/"+wallet.AddrBookFileName, 0) for i := range book { w.Write([]byte("<entry>")) w.Write([]byte("<addr>" + book[i].Enc58str + "</addr>")) w.Write([]byte("<label>")) xml.EscapeText(w, []byte(book[i].Extra.Label)) w.Write([]byte("</label>")) w.Write([]byte("<wallet>")) xml.EscapeText(w, []byte(book[i].Extra.Wallet)) w.Write([]byte("</wallet>")) w.Write([]byte("</entry>")) } w.Write([]byte("</addrbook>")) }
func (x *xmlObj) marshal() []byte { b := new(bytes.Buffer) for i := 0; i < len(x.xt); i++ { switch token := x.xt[i].token.(type) { case xml.StartElement: if token.Name.Space == "" { b.WriteString("<" + token.Name.Local) } else { b.WriteString("<" + token.Name.Space + ":" + token.Name.Local) } for _, attr := range token.Attr { b.WriteByte(' ') if attr.Name.Space == "" { b.WriteString(attr.Name.Local + "=\"" + attr.Value + "\"") } else { b.WriteString(attr.Name.Space + ":" + attr.Name.Local + "=\"" + attr.Value + "\"") } } b.WriteByte('>') case xml.EndElement: if token.Name.Space == "" { b.WriteString("</" + token.Name.Local) } else { b.WriteString("</" + token.Name.Space + ":" + token.Name.Local) } b.WriteByte('>') case xml.CharData: if x.xt[i].isData { xml.EscapeText(b, token) } else { b.Write(token) } case xml.ProcInst: b.WriteString("<?" + token.Target + " ") b.Write(token.Inst) b.WriteString("?>") case xml.Directive: b.WriteString("<!") b.Write(token) b.WriteString(">") case xml.Comment: b.WriteString("<!--") b.Write(token) b.WriteString("-->") } } return b.Bytes() }
func encodeDomainInfo(buf *bytes.Buffer, domain string) error { buf.Reset() buf.WriteString(xmlCommandPrefix) buf.WriteString(`<info>`) buf.WriteString(`<domain:info xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">`) buf.WriteString(`<domain:name>`) xml.EscapeText(buf, []byte(domain)) buf.WriteString(`</domain:name>`) buf.WriteString(`</domain:info>`) buf.WriteString(`</info>`) buf.WriteString(xmlCommandSuffix) return nil }
func (this *Node) printElement() []byte { var b bytes.Buffer if len(this.Name.Space) > 0 { b.WriteRune('<') b.WriteString(this.Name.Space) b.WriteRune(':') b.WriteString(this.Name.Local) } else { b.WriteRune('<') b.WriteString(this.Name.Local) } for _, v := range this.Attributes { if len(v.Name.Space) > 0 { prefix := this.spacePrefix(v.Name.Space) b.WriteString(fmt.Sprintf(` %s:%s="%s"`, prefix, v.Name.Local, v.Value)) } else { b.WriteString(fmt.Sprintf(` %s="%s"`, v.Name.Local, v.Value)) } } if len(this.Children) == 0 && len(this.Value) == 0 { b.WriteString(" />") return b.Bytes() } b.WriteRune('>') for _, v := range this.Children { b.Write(v.bytes()) } xml.EscapeText(&b, []byte(this.Value)) if len(this.Name.Space) > 0 { b.WriteString("</") b.WriteString(this.Name.Space) b.WriteRune(':') b.WriteString(this.Name.Local) b.WriteRune('>') } else { b.WriteString("</") b.WriteString(this.Name.Local) b.WriteRune('>') } return b.Bytes() }
// Look for command to execute from request body. The request/response content conform to Twilio SMS hook requirements. func (sh *WebShell) httpAPIMessage(w http.ResponseWriter, r *http.Request) { if cmd := sh.cmdFind(r.FormValue("Body")); cmd == "" { // No match, don't give much clue to the client though. http.Error(w, "404 page not found", http.StatusNotFound) } else { output := sh.cmdRun(cmd, sh.WebTimeoutSec, sh.WebTruncateLen, true, true) var escapeOutput bytes.Buffer if err := xml.EscapeText(&escapeOutput, []byte(output)); err != nil { log.Printf("XML escape failed - %v", err) } w.Header().Set("Content-Type", "text/xml") w.Header().Set("Cache-Control", "must-revalidate") w.WriteHeader(http.StatusOK) w.Write([]byte(fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?> <Response><Message>%s</Message></Response> `, escapeOutput.String()))) } }
func encodeDomainUpdateDS(buf *bytes.Buffer, domain string, add []DSRecord, rem []DSRecord) error { buf.Reset() buf.WriteString(xmlCommandPrefix) buf.WriteString(`<update>`) buf.WriteString(`<domain:update xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">`) buf.WriteString(`<domain:name>`) xml.EscapeText(buf, []byte(domain)) buf.WriteString(`</domain:name>`) buf.WriteString(`</domain:update>`) buf.WriteString(`</update>`) buf.WriteString(`<extension>`) buf.WriteString(`<secDNS:update xmlns:secDNS="urn:ietf:params:xml:ns:secDNS-1.1">`) if len(rem) > 0 { buf.WriteString(`<secDNS:rem>`) for _, dsr := range rem { buf.WriteString(`<secDNS:dsData>`) buf.WriteString(fmt.Sprintf(`<secDNS:keyTag>%d</secDNS:keyTag>`, dsr.KeyTag)) buf.WriteString(fmt.Sprintf(`<secDNS:alg>%d</secDNS:alg>`, dsr.Algorithm)) buf.WriteString(fmt.Sprintf(`<secDNS:digestType>%d</secDNS:digestType>`, dsr.DigestType)) buf.WriteString(fmt.Sprintf(`<secDNS:digest>%s</secDNS:digest>`, dsr.Digest)) buf.WriteString(`</secDNS:dsData>`) } buf.WriteString(`</secDNS:rem>`) } if len(add) > 0 { buf.WriteString(`<secDNS:add>`) for _, dsr := range add { buf.WriteString(`<secDNS:dsData>`) buf.WriteString(fmt.Sprintf(`<secDNS:keyTag>%d</secDNS:keyTag>`, dsr.KeyTag)) buf.WriteString(fmt.Sprintf(`<secDNS:alg>%d</secDNS:alg>`, dsr.Algorithm)) buf.WriteString(fmt.Sprintf(`<secDNS:digestType>%d</secDNS:digestType>`, dsr.DigestType)) buf.WriteString(fmt.Sprintf(`<secDNS:digest>%s</secDNS:digest>`, dsr.Digest)) buf.WriteString(`</secDNS:dsData>`) } buf.WriteString(`</secDNS:add>`) } buf.WriteString(`</secDNS:update>`) buf.WriteString(`</extension>`) buf.WriteString(xmlCommandSuffix) return nil }
func escapeXML(s string) string { for i := 0; i < len(s); i++ { // As an optimization, if s contains only ASCII letters, digits or a // few special characters, the escaped value is s itself and we don't // need to allocate a buffer and convert between string and []byte. switch c := s[i]; { case c == ' ' || c == '_' || ('+' <= c && c <= '9') || // Digits as well as + , - . and / ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'): continue } // Otherwise, go through the full escaping process. var buf bytes.Buffer xml.EscapeText(&buf, []byte(s)) return buf.String() } return s }
func (e *Encoder) Attribute(space, local, value string) error { var err error if e.openStartTag { aname := local if space != "" { prefix, ok := e.namespaces[space] if !ok || prefix == "" { return errors.New("no prefix for namespace " + space) } aname = prefix + ":" + local } if _, err = e.w.WriteString(" " + aname + `="`); err == nil { if err = xml.EscapeText(e.w, []byte(value)); err == nil { _, err = e.w.WriteString(`"`) } } } else { err = errors.New(`attribute after ">"`) } return err }