?
This document uses PHP Chinese website manual Release
import "encoding/xml"
Overview
Index
Examples
Package xml實(shí)現(xiàn)了一個(gè)理解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是應(yīng)被視為自動(dòng)關(guān)閉的一組HTML元素。
var HTMLAutoClose = htmlAutoClose
HTMLEntity是包含標(biāo)準(zhǔn)HTML實(shí)體字符翻譯的實(shí)體映射。
var HTMLEntity = htmlEntity
func Escape(w io.Writer, s []byte)
Escape與EscapeText類似,但省略了錯(cuò)誤返回值。它提供了與Go 1.0的向后兼容性。代碼定位Go 1.1或更高版本應(yīng)該使用EscapeText。
func EscapeText(w io.Writer, s []byte) error
EscapeText寫入正確轉(zhuǎn)義的純文本數(shù)據(jù)的XML等價(jià)物。
func Marshal(v interface{}) ([]byte, error)
Marshal返回v的XML編碼。
Marshal通過封送每個(gè)元素來處理數(shù)組或片段。Marshal通過編組指向的值處理指針,如果指針為零,則不寫任何內(nèi)容。Marshal通過封送其包含的值來處理接口值,或者如果接口值為零,則不寫任何內(nèi)容。Marshal通過編寫一個(gè)或多個(gè)包含數(shù)據(jù)的XML元素來處理所有其他數(shù)據(jù)。
XML元素的名稱取自優(yōu)先順序:
- 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
結(jié)構(gòu)的XML元素包含每個(gè)結(jié)構(gòu)導(dǎo)出字段的封送元素,但有以下例外:
- 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.
如果一個(gè)字段使用標(biāo)簽“a> b> c”,那么元素c將嵌套在父元素a和b中。名稱相同的父對(duì)象旁邊出現(xiàn)的字段將被包含在一個(gè)XML元素中。
以MarshalIndent為例。
如果要求編組頻道,功能或地圖,元帥將返回錯(cuò)誤。
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
MarshalIndent的工作方式與Marshal相同,但每個(gè)XML元素都以一個(gè)新的縮進(jìn)行開始,該行以前綴開頭,后跟一個(gè)或多個(gè)根據(jù)嵌套深度縮進(jìn)的縮進(jìn)副本。
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編碼的數(shù)據(jù)并將結(jié)果存儲(chǔ)在v指向的值中,該值必須是任意的結(jié)構(gòu)體,切片或字符串。丟棄不適合v的格式良好的數(shù)據(jù)。
由于Unmarshal使用反射包,因此它只能分配給導(dǎo)出(大寫)字段。Unmarshal使用區(qū)分大小寫的比較來將XML元素名稱與標(biāo)記值和結(jié)構(gòu)字段名稱進(jìn)行匹配。
Unmarshal使用以下規(guī)則將XML元素映射到結(jié)構(gòu)。在規(guī)則中,字段的標(biāo)記引用與struct字段標(biāo)記中的鍵'xml'關(guān)聯(lián)的值(請(qǐng)參見上面的示例)。
* 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元素映射到字符串或[]字節(jié),方法是將該元素的字符數(shù)據(jù)串聯(lián)在字符串或[]字節(jié)中。保存的[]字節(jié)永遠(yuǎn)不會(huì)為零。
Unmarshal通過將值保存在字符串或切片中將屬性值映射到字符串或[]字節(jié)。
Unmarshal通過將屬性(包括其名稱)保存在Attr中將屬性值映射到Attr。
Unmarshal通過擴(kuò)展切片的長度并將元素或?qū)傩杂成涞叫聞?chuàng)建的值來將XML元素或?qū)傩灾涤成涞角衅?/p>
Unmarshal通過將XML元素或?qū)傩灾翟O(shè)置為由字符串表示的布爾值來映射XML元素或?qū)傩灾怠?/p>
Unmarshal通過將字段設(shè)置為以十進(jìn)制解釋字符串值的結(jié)果將XML元素或?qū)傩灾涤成涞秸麛?shù)或浮點(diǎn)字段。沒有檢查溢出。
Unmarshal通過記錄元素名稱將XML元素映射到名稱。
Unmarshal通過將指針設(shè)置為新分配的值,然后將該元素映射到該值,將XML元素映射到指針。
缺少的元素或空屬性值將被解組為零值。如果該字段是切片,則會(huì)將零值附加到該字段。否則,該字段將被設(shè)置為其零值。
本示例演示了將XML摘錄解編到具有某些預(yù)設(shè)字段的值中。請(qǐng)注意,Phone字段未被修改,并且XML <Company>元素被忽略。此外,Groups字段是考慮到其標(biāo)簽中提供的元素路徑分配的。
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
評(píng)論表示形式為<!--comment-->的XML注釋。這些字節(jié)不包括<!-- and -->注釋標(biāo)記。
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中創(chuàng)建一個(gè)新的XML分析器。如果r沒有實(shí)現(xiàn)io.ByteReader,NewDecoder會(huì)自行緩沖。
func (d *Decoder) Decode(v interface{}) error
解碼像Unmarshal一樣工作,除了它讀取解碼器流以查找開始元素。
func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error
DecodeElement的工作方式與Unmarshal類似,只不過它需要一個(gè)指向開始XML元素的指針來解碼為v。當(dāng)客戶端讀取一些原始XML令牌本身時(shí),它也很有用,但也希望延遲Unmarshal的某些元素。
func (d *Decoder) InputOffset() int64
InputOffset返回當(dāng)前解碼器位置的輸入流字節(jié)偏移量。偏移量給出了最近返回的標(biāo)記的結(jié)束位置和下一個(gè)標(biāo)記的開始位置。
func (d *Decoder) RawToken() (Token, error)
RawToken與Token類似,但不驗(yàn)證開始和結(jié)束元素是否匹配,也不會(huì)將名稱空間前綴轉(zhuǎn)換為相應(yīng)的URL。
func (d *Decoder) Skip() error
跳過讀取標(biāo)記,直到它消耗了與已經(jīng)消耗的最近開始元素相匹配的結(jié)束元素。如果它遇到一個(gè)開始元素,它會(huì)重新出現(xiàn),所以它可以用來跳過嵌套結(jié)構(gòu)。如果找到匹配start元素的結(jié)束元素,則返回nil; 否則會(huì)返回描述問題的錯(cuò)誤。
func (d *Decoder) Token() (Token, error)
令牌返回輸入流中的下一個(gè)XML令牌。在輸入流結(jié)束時(shí),令牌返回nil,io.EOF。
返回的標(biāo)記數(shù)據(jù)中的字節(jié)片段指的是解析器的內(nèi)部緩沖區(qū),并且僅在下一次調(diào)用Token之前保持有效。要獲取字節(jié)的副本,請(qǐng)調(diào)用CopyToken或標(biāo)記的Copy方法。
令牌將自閉元素?cái)U(kuò)展為由連續(xù)調(diào)用返回的獨(dú)立開始和結(jié)束元素。
令牌保證它返回的StartElement和EndElement令牌被正確嵌套和匹配:如果令牌在所有預(yù)期的結(jié)束元素之前遇到意外的結(jié)束元素或EOF,它將返回一個(gè)錯(cuò)誤。
Token按照http://www.w3.org/TR/REC-xml-names/所述實(shí)現(xiàn)XML名稱空間。Token中包含的每個(gè)Name結(jié)構(gòu)都將空間設(shè)置為識(shí)別其名稱空間的URL。如果令牌遇到無法識(shí)別的名稱空間前綴,它將使用前綴作為空格,而不是報(bào)告錯(cuò)誤。
指令表示<!text>格式的XML指令。字節(jié)不包含<!和>標(biāo)記。
type Directive []byte
func (d Directive) Copy() Directive
編碼器將XML數(shù)據(jù)寫入輸出流。
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返回一個(gè)寫入w的新編碼器。
func (enc *Encoder) Encode(v interface{}) error
編碼將v的XML編碼寫入流。
有關(guān)將Go值轉(zhuǎn)換為XML的詳細(xì)信息,請(qǐng)參閱Marshal的文檔。
在返回之前編碼呼叫刷新。
func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error
EncodeElement將v的XML編碼寫入流,使用start作為編碼中最外層的標(biāo)記。
有關(guān)將Go值轉(zhuǎn)換為XML的詳細(xì)信息,請(qǐng)參閱Marshal的文檔。
EncodeElement在返回之前調(diào)用Flush。
func (enc *Encoder) EncodeToken(t Token) error
EncodeToken將給定的XML令牌寫入流中。如果StartElement和EndElement標(biāo)記沒有正確匹配,它將返回一個(gè)錯(cuò)誤。
EncodeToken不會(huì)調(diào)用Flush,因?yàn)樗ǔJ荅ncode或EncodeElement(或在這些操作期間調(diào)用的自定義Marshaler的MarshalXML)的較大操作的一部分,并且在完成時(shí)會(huì)調(diào)用Flush。創(chuàng)建編碼器然后直接調(diào)用EncodeToken而不使用Encode或EncodeElement的調(diào)用者在完成后需要調(diào)用Flush,以確保將XML寫入底層編寫器。
EncodeToken只允許將Target設(shè)置為“xml”的ProcInst作為流中的第一個(gè)標(biāo)記。
func (enc *Encoder) Flush() error
刷新將任何緩沖的XML刷新到底層寫入器。有關(guān)何時(shí)需要的詳細(xì)信息,請(qǐng)參閱EncodeToken文檔。
func (enc *Encoder) Indent(prefix, indent string)
縮進(jìn)將編碼器設(shè)置為生成XML,其中每個(gè)元素都以新的縮進(jìn)行開頭,縮進(jìn)行以前綴開頭,后跟縮進(jìn)的一個(gè)或多個(gè)副本(根據(jù)嵌套深度)。
EndElement表示一個(gè)XML結(jié)束元素。
type EndElement struct { Name Name}
Marshaler是由對(duì)象實(shí)現(xiàn)的接口,可以將自己編組為有效的XML元素。
MarshalXML將接收器編碼為零個(gè)或多個(gè)XML元素。按照慣例,數(shù)組或片通常被編碼為一系列元素,每個(gè)條目一個(gè)。不需要使用start作為元素標(biāo)記,但這樣做可以使Unmarshal將XML元素與正確的struct字段進(jìn)行匹配。一種常見的實(shí)現(xiàn)策略是使用與所需XML相對(duì)應(yīng)的布局構(gòu)造一個(gè)單獨(dú)的值,然后使用e.EncodeElement對(duì)其進(jìn)行編碼。另一種常見策略是對(duì)e.EncodeToken使用重復(fù)調(diào)用來一次生成一個(gè)令牌的XML輸出。編碼令牌的序列必須組成零個(gè)或多個(gè)有效的XML元素。
type Marshaler interface { MarshalXML(e *Encoder, start StartElement) error}
MarshalerAttr是由對(duì)象實(shí)現(xiàn)的接口,可以將自己編組為有效的XML屬性。
MarshalXMLAttr返回一個(gè)XML屬性和接收者的編碼值。使用name作為屬性名稱不是必需的,但這樣做將使Unmarshal能夠?qū)⒃搶傩耘c正確的struct字段進(jìn)行匹配。如果MarshalXMLAttr返回零屬性Attr {},則不會(huì)在輸出中生成任何屬性。MarshalXMLAttr僅用于字段標(biāo)簽中具有“attr”選項(xiàng)的結(jié)構(gòu)字段。
type MarshalerAttr interface { MarshalXMLAttr(name Name) (Attr, error)}
名稱表示用名稱空間標(biāo)識(shí)符(空格)注釋的XML名稱(本地)。在由Decoder.Token返回的令牌中,空間標(biāo)識(shí)符是作為規(guī)范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返回相應(yīng)的XML結(jié)束元素。
A SyntaxError represents a syntax error in the XML input stream.
type SyntaxError struct { Msg string Line int}
func (e *SyntaxError) Error() string
TagPathError表示由于使用帶有沖突路徑的字段標(biāo)記而導(dǎo)致解組過程中出現(xiàn)錯(cuò)誤。
type TagPathError struct { Struct reflect.Type Field1, Tag1 string Field2, Tag2 string}
func (e *TagPathError) Error() string
令牌是一個(gè)持有令牌類型之一的接口:StartElement,EndElement,CharData,Comment,ProcInst或Directive。
type Token interface{}
func CopyToken(t Token) Token
CopyToken返回一個(gè)令牌的副本。
UnmarshalError表示解組過程中的錯(cuò)誤。
type UnmarshalError string
func (e UnmarshalError) Error() string
Unmarshaler是可以解組自己的XML元素描述的對(duì)象實(shí)現(xiàn)的接口。
UnmarshalXML解碼從給定的開始元素開始的單個(gè)XML元素。如果它返回一個(gè)錯(cuò)誤,對(duì)Unmarshal的外部調(diào)用將停止并返回該錯(cuò)誤。UnmarshalXML必須使用一個(gè)XML元素。一種常見的實(shí)現(xiàn)策略是使用d.DecodeElement解組為一個(gè)單獨(dú)的值,其布局與預(yù)期的XML匹配,然后將該值中的數(shù)據(jù)復(fù)制到接收器中。另一個(gè)常用策略是使用d.Token一次處理XML對(duì)象的一個(gè)令牌。UnmarshalXML不能使用d.RawToken。
type Unmarshaler interface { UnmarshalXML(d *Decoder, start StartElement) error}
UnmarshalerAttr是由可以解組自己的XML屬性描述的對(duì)象實(shí)現(xiàn)的接口。
UnmarshalXMLAttr解碼單個(gè)XML屬性。如果它返回一個(gè)錯(cuò)誤,對(duì)Unmarshal的外部調(diào)用將停止并返回該錯(cuò)誤。UnmarshalXMLAttr僅用于字段標(biāo)簽中具有“attr”選項(xiàng)的結(jié)構(gòu)字段。
type UnmarshalerAttr interface { UnmarshalXMLAttr(attr Attr) error}
MarshalXMLError在Marshal遇到無法轉(zhuǎn)換為XML的類型時(shí)返回。
type UnsupportedTypeError struct { Type reflect.Type}
func (e *UnsupportedTypeError) Error() string
?XML 元素和數(shù)據(jù)結(jié)構(gòu)之間的映射本質(zhì)上是有缺陷的:XML元素是匿名值的依賴于順序的集合,而數(shù)據(jù)結(jié)構(gòu)是與命令值無關(guān)的順序無關(guān)集合。查看包json以獲得更適合數(shù)據(jù)結(jié)構(gòu)的文本表示。