©
This document uses PHP Chinese website manual Release
import "encoding/xml"
Overview
Index
Examples
Package xml实现了一个理解XML名称空间的简单XML 1.0分析器。
Constants
Variables
func Escape(w io.Writer, s []byte)
func EscapeText(w io.Writer, s []byte) error
func Marshal(v interface{}) ([]byte, error)
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error
type Attr
type CharData
func (c CharData) Copy() CharData
type Comment
func (c Comment) Copy() Comment
type Decoder
func NewDecoder(r io.Reader) *Decoder
func (d *Decoder) Decode(v interface{}) error
func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error
func (d *Decoder) InputOffset() int64
func (d *Decoder) RawToken() (Token, error)
func (d *Decoder) Skip() error
func (d *Decoder) Token() (Token, error)
type Directive
func (d Directive) Copy() Directive
type Encoder
func NewEncoder(w io.Writer) *Encoder
func (enc *Encoder) Encode(v interface{}) error
func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error
func (enc *Encoder) EncodeToken(t Token) error
func (enc *Encoder) Flush() error
func (enc *Encoder) Indent(prefix, indent string)
type EndElement
type Marshaler
type MarshalerAttr
type Name
type ProcInst
func (p ProcInst) Copy() ProcInst
type StartElement
func (e StartElement) Copy() StartElement
func (e StartElement) End() EndElement
type SyntaxError
func (e *SyntaxError) Error() string
type TagPathError
func (e *TagPathError) Error() string
type Token
func CopyToken(t Token) Token
type UnmarshalError
func (e UnmarshalError) Error() string
type Unmarshaler
type UnmarshalerAttr
type UnsupportedTypeError
func (e *UnsupportedTypeError) Error() string
Bugs
Encoder MarshalIndent Unmarshal
marshal.go read.go typeinfo.go xml.go
const ( // A generic XML header suitable for use with the output of Marshal. // This is not automatically added to any output of this package, // it is provided as a convenience. Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n")
HTMLAutoClose是应被视为自动关闭的一组HTML元素。
var HTMLAutoClose = htmlAutoClose
HTMLEntity是包含标准HTML实体字符翻译的实体映射。
var HTMLEntity = htmlEntity
func Escape(w io.Writer, s []byte)
Escape与EscapeText类似,但省略了错误返回值。它提供了与Go 1.0的向后兼容性。代码定位Go 1.1或更高版本应该使用EscapeText。
func EscapeText(w io.Writer, s []byte) error
EscapeText写入正确转义的纯文本数据的XML等价物。
func Marshal(v interface{}) ([]byte, error)
Marshal返回v的XML编码。
Marshal通过封送每个元素来处理数组或片段。Marshal通过编组指向的值处理指针,如果指针为零,则不写任何内容。Marshal通过封送其包含的值来处理接口值,或者如果接口值为零,则不写任何内容。Marshal通过编写一个或多个包含数据的XML元素来处理所有其他数据。
XML元素的名称取自优先顺序:
- the tag on the XMLName field, if the data is a struct- the value of the XMLName field of type Name- the tag of the struct field used to obtain the data- the name of the struct field used to obtain the data- the name of the marshaled type
结构的XML元素包含每个结构导出字段的封送元素,但有以下例外:
- the XMLName field, described above, is omitted.- a field with tag "-" is omitted.- a field with tag "name,attr" becomes an attribute with the given name in the XML element.- a field with tag ",attr" becomes an attribute with the field name in the XML element.- a field with tag ",chardata" is written as character data, not as an XML element.- a field with tag ",cdata" is written as character data wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.- a field with tag ",innerxml" is written verbatim, not subject to the usual marshaling procedure.- a field with tag ",comment" is written as an XML comment, not subject to the usual marshaling procedure. It must not contain the "--" string within it.- a field with a tag including the "omitempty" option is omitted if the field value is empty. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.- an anonymous struct field is handled as if the fields of its value were part of the outer struct.
如果一个字段使用标签“a> b> c”,那么元素c将嵌套在父元素a和b中。名称相同的父对象旁边出现的字段将被包含在一个XML元素中。
以MarshalIndent为例。
如果要求编组频道,功能或地图,元帅将返回错误。
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
MarshalIndent的工作方式与Marshal相同,但每个XML元素都以一个新的缩进行开始,该行以前缀开头,后跟一个或多个根据嵌套深度缩进的缩进副本。
package mainimport ("encoding/xml""fmt""os")func main() { type Address struct { City, State string} type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"`} v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} v.Comment = " Need more details. " v.Address = Address{"Hanga Roa", "Easter Island"} output, err := xml.MarshalIndent(v, " ", " ")if err != nil { fmt.Printf("error: %v\n", err)} os.Stdout.Write(output)}
func Unmarshal(data []byte, v interface{}) error
Unmarshal解析XML编码的数据并将结果存储在v指向的值中,该值必须是任意的结构体,切片或字符串。丢弃不适合v的格式良好的数据。
由于Unmarshal使用反射包,因此它只能分配给导出(大写)字段。Unmarshal使用区分大小写的比较来将XML元素名称与标记值和结构字段名称进行匹配。
Unmarshal使用以下规则将XML元素映射到结构。在规则中,字段的标记引用与struct字段标记中的键'xml'关联的值(请参见上面的示例)。
* If the struct has a field of type []byte or string with tag ",innerxml", Unmarshal accumulates the raw XML nested inside the element in that field. The rest of the rules still apply.* If the struct has a field named XMLName of type Name, Unmarshal records the element name in that field.* If the XMLName field has an associated tag of the form "name" or "namespace-URL name", the XML element must have the given name (and, optionally, name space) or else Unmarshal returns an error.* If the XML element has an attribute whose name matches a struct field name with an associated tag containing ",attr" or the explicit name in a struct field tag of the form "name,attr", Unmarshal records the attribute value in that field.* If the XML element has an attribute not handled by the previous rule and the struct has a field with an associated tag containing ",any,attr", Unmarshal records the attribute value in the first such field.* If the XML element contains character data, that data is accumulated in the first struct field that has tag ",chardata". The struct field may have type []byte or string. If there is no such field, the character data is discarded.* If the XML element contains comments, they are accumulated in the first struct field that has tag ",comment". The struct field may have type []byte or string. If there is no such field, the comments are discarded.* If the XML element contains a sub-element whose name matches the prefix of a tag formatted as "a" or "a>b>c", unmarshal will descend into the XML structure looking for elements with the given names, and will map the innermost elements to that struct field. A tag starting with ">" is equivalent to one starting with the field name followed by ">".* If the XML element contains a sub-element whose name matches a struct field's XMLName tag and the struct field has no explicit name tag as per the previous rule, unmarshal maps the sub-element to that struct field.* If the XML element contains a sub-element whose name matches a field without any mode flags (",attr", ",chardata", etc), Unmarshal maps the sub-element to that struct field.* If the XML element contains a sub-element that hasn't matched any of the above rules and the struct has a field with tag ",any", unmarshal maps the sub-element to that struct field.* An anonymous struct field is handled as if the fields of its value were part of the outer struct.* A struct field with tag "-" is never unmarshaled into.
Unmarshal将XML元素映射到字符串或[]字节,方法是将该元素的字符数据串联在字符串或[]字节中。保存的[]字节永远不会为零。
Unmarshal通过将值保存在字符串或切片中将属性值映射到字符串或[]字节。
Unmarshal通过将属性(包括其名称)保存在Attr中将属性值映射到Attr。
Unmarshal通过扩展切片的长度并将元素或属性映射到新创建的值来将XML元素或属性值映射到切片。
Unmarshal通过将XML元素或属性值设置为由字符串表示的布尔值来映射XML元素或属性值。
Unmarshal通过将字段设置为以十进制解释字符串值的结果将XML元素或属性值映射到整数或浮点字段。没有检查溢出。
Unmarshal通过记录元素名称将XML元素映射到名称。
Unmarshal通过将指针设置为新分配的值,然后将该元素映射到该值,将XML元素映射到指针。
缺少的元素或空属性值将被解组为零值。如果该字段是切片,则会将零值附加到该字段。否则,该字段将被设置为其零值。
本示例演示了将XML摘录解编到具有某些预设字段的值中。请注意,Phone字段未被修改,并且XML <Company>元素被忽略。此外,Groups字段是考虑到其标签中提供的元素路径分配的。
package mainimport ("encoding/xml""fmt")func main() { type Email struct { Where string `xml:"where,attr"` Addr string} type Address struct { City, State string} type Result struct { XMLName xml.Name `xml:"Person"` Name string `xml:"FullName"` Phone string Email []Email Groups []string `xml:"Group>Value"` Address} v := Result{Name: "none", Phone: "none"} data := ` <Person> <FullName>Grace R. Emlin</FullName> <Company>Example Inc.</Company> <Email where="home"> <Addr>gre@example.com</Addr> </Email> <Email where='work'> <Addr>gre@work.com</Addr> </Email> <Group> <Value>Friends</Value> <Value>Squash</Value> </Group> <City>Hanga Roa</City> <State>Easter Island</State> </Person> ` err := xml.Unmarshal([]byte(data), &v)if err != nil { fmt.Printf("error: %v", err)return} fmt.Printf("XMLName: %#v\n", v.XMLName) fmt.Printf("Name: %q\n", v.Name) fmt.Printf("Phone: %q\n", v.Phone) fmt.Printf("Email: %v\n", v.Email) fmt.Printf("Groups: %v\n", v.Groups) fmt.Printf("Address: %v\n", v.Address)}
Attr表示XML元素中的属性(Name = Value)。
type Attr struct { Name Name Value string}
A CharData represents XML character data (raw text), in which XML escape sequences have been replaced by the characters they represent.
type CharData []byte
func (c CharData) Copy() CharData
评论表示形式为<!--comment-->的XML注释。这些字节不包括<!-- and -->注释标记。
type Comment []byte
func (c Comment) Copy() Comment
解码器代表读取特定输入流的XML解析器。解析器假定它的输入是用UTF-8编码的。
type Decoder struct { // Strict defaults to true, enforcing the requirements // of the XML specification. // If set to false, the parser allows input containing common // mistakes: // * If an element is missing an end tag, the parser invents // end tags as necessary to keep the return values from Token // properly balanced. // * In attribute values and character data, unknown or malformed // character entities (sequences beginning with &) are left alone. // // Setting: // // d.Strict = false; // d.AutoClose = HTMLAutoClose; // d.Entity = HTMLEntity // // creates a parser that can handle typical HTML. // // Strict mode does not enforce the requirements of the XML name spaces TR. // In particular it does not reject name space tags using undefined prefixes. // Such tags are recorded with the unknown prefix as the name space URL. Strict bool // When Strict == false, AutoClose indicates a set of elements to // consider closed immediately after they are opened, regardless // of whether an end element is present. AutoClose []string // Entity can be used to map non-standard entity names to string replacements. // The parser behaves as if these standard mappings are present in the map, // regardless of the actual map content: // // "lt": "<", // "gt": ">", // "amp": "&", // "apos": "'", // "quot": `"`, Entity map[string]string // CharsetReader, if non-nil, defines a function to generate // charset-conversion readers, converting from the provided // non-UTF-8 charset into UTF-8. If CharsetReader is nil or // returns an error, parsing stops with an error. One of the // the CharsetReader's result values must be non-nil. CharsetReader func(charset string, input io.Reader) (io.Reader, error) // DefaultSpace sets the default name space used for unadorned tags, // as if the entire XML stream were wrapped in an element containing // the attribute xmlns="DefaultSpace". DefaultSpace string // contains filtered or unexported fields}
func NewDecoder(r io.Reader) *Decoder
NewDecoder从r中创建一个新的XML分析器。如果r没有实现io.ByteReader,NewDecoder会自行缓冲。
func (d *Decoder) Decode(v interface{}) error
解码像Unmarshal一样工作,除了它读取解码器流以查找开始元素。
func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error
DecodeElement的工作方式与Unmarshal类似,只不过它需要一个指向开始XML元素的指针来解码为v。当客户端读取一些原始XML令牌本身时,它也很有用,但也希望延迟Unmarshal的某些元素。
func (d *Decoder) InputOffset() int64
InputOffset返回当前解码器位置的输入流字节偏移量。偏移量给出了最近返回的标记的结束位置和下一个标记的开始位置。
func (d *Decoder) RawToken() (Token, error)
RawToken与Token类似,但不验证开始和结束元素是否匹配,也不会将名称空间前缀转换为相应的URL。
func (d *Decoder) Skip() error
跳过读取标记,直到它消耗了与已经消耗的最近开始元素相匹配的结束元素。如果它遇到一个开始元素,它会重新出现,所以它可以用来跳过嵌套结构。如果找到匹配start元素的结束元素,则返回nil; 否则会返回描述问题的错误。
func (d *Decoder) Token() (Token, error)
令牌返回输入流中的下一个XML令牌。在输入流结束时,令牌返回nil,io.EOF。
返回的标记数据中的字节片段指的是解析器的内部缓冲区,并且仅在下一次调用Token之前保持有效。要获取字节的副本,请调用CopyToken或标记的Copy方法。
令牌将自闭元素扩展为由连续调用返回的独立开始和结束元素。
令牌保证它返回的StartElement和EndElement令牌被正确嵌套和匹配:如果令牌在所有预期的结束元素之前遇到意外的结束元素或EOF,它将返回一个错误。
Token按照http://www.w3.org/TR/REC-xml-names/所述实现XML名称空间。Token中包含的每个Name结构都将空间设置为识别其名称空间的URL。如果令牌遇到无法识别的名称空间前缀,它将使用前缀作为空格,而不是报告错误。
指令表示<!text>格式的XML指令。字节不包含<!和>标记。
type Directive []byte
func (d Directive) Copy() Directive
编码器将XML数据写入输出流。
type Encoder struct { // contains filtered or unexported fields}
package mainimport ("encoding/xml""fmt""os")func main() { type Address struct { City, State string} type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"`} v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} v.Comment = " Need more details. " v.Address = Address{"Hanga Roa", "Easter Island"} enc := xml.NewEncoder(os.Stdout) enc.Indent(" ", " ")if err := enc.Encode(v); err != nil { fmt.Printf("error: %v\n", err)}}
func NewEncoder(w io.Writer) *Encoder
NewEncoder返回一个写入w的新编码器。
func (enc *Encoder) Encode(v interface{}) error
编码将v的XML编码写入流。
有关将Go值转换为XML的详细信息,请参阅Marshal的文档。
在返回之前编码呼叫刷新。
func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error
EncodeElement将v的XML编码写入流,使用start作为编码中最外层的标记。
有关将Go值转换为XML的详细信息,请参阅Marshal的文档。
EncodeElement在返回之前调用Flush。
func (enc *Encoder) EncodeToken(t Token) error
EncodeToken将给定的XML令牌写入流中。如果StartElement和EndElement标记没有正确匹配,它将返回一个错误。
EncodeToken不会调用Flush,因为它通常是Encode或EncodeElement(或在这些操作期间调用的自定义Marshaler的MarshalXML)的较大操作的一部分,并且在完成时会调用Flush。创建编码器然后直接调用EncodeToken而不使用Encode或EncodeElement的调用者在完成后需要调用Flush,以确保将XML写入底层编写器。
EncodeToken只允许将Target设置为“xml”的ProcInst作为流中的第一个标记。
func (enc *Encoder) Flush() error
刷新将任何缓冲的XML刷新到底层写入器。有关何时需要的详细信息,请参阅EncodeToken文档。
func (enc *Encoder) Indent(prefix, indent string)
缩进将编码器设置为生成XML,其中每个元素都以新的缩进行开头,缩进行以前缀开头,后跟缩进的一个或多个副本(根据嵌套深度)。
EndElement表示一个XML结束元素。
type EndElement struct { Name Name}
Marshaler是由对象实现的接口,可以将自己编组为有效的XML元素。
MarshalXML将接收器编码为零个或多个XML元素。按照惯例,数组或片通常被编码为一系列元素,每个条目一个。不需要使用start作为元素标记,但这样做可以使Unmarshal将XML元素与正确的struct字段进行匹配。一种常见的实现策略是使用与所需XML相对应的布局构造一个单独的值,然后使用e.EncodeElement对其进行编码。另一种常见策略是对e.EncodeToken使用重复调用来一次生成一个令牌的XML输出。编码令牌的序列必须组成零个或多个有效的XML元素。
type Marshaler interface { MarshalXML(e *Encoder, start StartElement) error}
MarshalerAttr是由对象实现的接口,可以将自己编组为有效的XML属性。
MarshalXMLAttr返回一个XML属性和接收者的编码值。使用name作为属性名称不是必需的,但这样做将使Unmarshal能够将该属性与正确的struct字段进行匹配。如果MarshalXMLAttr返回零属性Attr {},则不会在输出中生成任何属性。MarshalXMLAttr仅用于字段标签中具有“attr”选项的结构字段。
type MarshalerAttr interface { MarshalXMLAttr(name Name) (Attr, error)}
名称表示用名称空间标识符(空格)注释的XML名称(本地)。在由Decoder.Token返回的令牌中,空间标识符是作为规范URL提供的,而不是被解析文档中使用的短前缀。
type Name struct { Space, Local string}
ProcInst表示<?target inst?>形式的XML处理指令
type ProcInst struct { Target string Inst []byte}
func (p ProcInst) Copy() ProcInst
StartElement表示XML起始元素。
type StartElement struct { Name Name Attr []Attr}
func (e StartElement) Copy() StartElement
func (e StartElement) End() EndElement
End返回相应的XML结束元素。
A SyntaxError represents a syntax error in the XML input stream.
type SyntaxError struct { Msg string Line int}
func (e *SyntaxError) Error() string
TagPathError表示由于使用带有冲突路径的字段标记而导致解组过程中出现错误。
type TagPathError struct { Struct reflect.Type Field1, Tag1 string Field2, Tag2 string}
func (e *TagPathError) Error() string
令牌是一个持有令牌类型之一的接口:StartElement,EndElement,CharData,Comment,ProcInst或Directive。
type Token interface{}
func CopyToken(t Token) Token
CopyToken返回一个令牌的副本。
UnmarshalError表示解组过程中的错误。
type UnmarshalError string
func (e UnmarshalError) Error() string
Unmarshaler是可以解组自己的XML元素描述的对象实现的接口。
UnmarshalXML解码从给定的开始元素开始的单个XML元素。如果它返回一个错误,对Unmarshal的外部调用将停止并返回该错误。UnmarshalXML必须使用一个XML元素。一种常见的实现策略是使用d.DecodeElement解组为一个单独的值,其布局与预期的XML匹配,然后将该值中的数据复制到接收器中。另一个常用策略是使用d.Token一次处理XML对象的一个令牌。UnmarshalXML不能使用d.RawToken。
type Unmarshaler interface { UnmarshalXML(d *Decoder, start StartElement) error}
UnmarshalerAttr是由可以解组自己的XML属性描述的对象实现的接口。
UnmarshalXMLAttr解码单个XML属性。如果它返回一个错误,对Unmarshal的外部调用将停止并返回该错误。UnmarshalXMLAttr仅用于字段标签中具有“attr”选项的结构字段。
type UnmarshalerAttr interface { UnmarshalXMLAttr(attr Attr) error}
MarshalXMLError在Marshal遇到无法转换为XML的类型时返回。
type UnsupportedTypeError struct { Type reflect.Type}
func (e *UnsupportedTypeError) Error() string
☞XML 元素和数据结构之间的映射本质上是有缺陷的:XML元素是匿名值的依赖于顺序的集合,而数据结构是与命令值无关的顺序无关集合。查看包json以获得更适合数据结构的文本表示。