EncodeToken writes the given XML token to the stream. It returns an error if StartElement and EndElement tokens are not properly matched. EncodeToken does not call Flush, because usually it is part of a larger operation such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked dur
(t Token)
| 199 | // elements (including the StartElement itself) will use the declared |
| 200 | // prefix when encoding names with matching namespace URIs. |
| 201 | func (enc *Encoder) EncodeToken(t Token) error { |
| 202 | |
| 203 | p := &enc.p |
| 204 | switch t := t.(type) { |
| 205 | case StartElement: |
| 206 | if err := p.writeStart(&t); err != nil { |
| 207 | return err |
| 208 | } |
| 209 | case EndElement: |
| 210 | if err := p.writeEnd(t.Name); err != nil { |
| 211 | return err |
| 212 | } |
| 213 | case CharData: |
| 214 | escapeText(p, t, false) |
| 215 | case Comment: |
| 216 | if bytes.Contains(t, endComment) { |
| 217 | return fmt.Errorf("xml: EncodeToken of Comment containing --> marker") |
| 218 | } |
| 219 | p.WriteString("<!--") |
| 220 | p.Write(t) |
| 221 | p.WriteString("-->") |
| 222 | return p.cachedWriteError() |
| 223 | case ProcInst: |
| 224 | // First token to be encoded which is also a ProcInst with target of xml |
| 225 | // is the xml declaration. The only ProcInst where target of xml is allowed. |
| 226 | if t.Target == "xml" && p.Buffered() != 0 { |
| 227 | return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded") |
| 228 | } |
| 229 | if !isNameString(t.Target) { |
| 230 | return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target") |
| 231 | } |
| 232 | if bytes.Contains(t.Inst, endProcInst) { |
| 233 | return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker") |
| 234 | } |
| 235 | p.WriteString("<?") |
| 236 | p.WriteString(t.Target) |
| 237 | if len(t.Inst) > 0 { |
| 238 | p.WriteByte(' ') |
| 239 | p.Write(t.Inst) |
| 240 | } |
| 241 | p.WriteString("?>") |
| 242 | case Directive: |
| 243 | if !isValidDirective(t) { |
| 244 | return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers") |
| 245 | } |
| 246 | p.WriteString("<!") |
| 247 | p.Write(t) |
| 248 | p.WriteString(">") |
| 249 | default: |
| 250 | return fmt.Errorf("xml: EncodeToken of invalid token type") |
| 251 | |
| 252 | } |
| 253 | return p.cachedWriteError() |
| 254 | } |
| 255 | |
| 256 | // isValidDirective reports whether dir is a valid directive text, |
| 257 | // meaning angle brackets are matched, ignoring comments and strings. |