This commit is contained in:
badkaktus 2019-10-09 22:17:28 +03:00
parent 1660a57d5f
commit bee3c75b76

View File

@ -1,5 +1,5 @@
// Go offers built-in support for XML and XML-like
// formats with the `encoding.xml` package.
// Go предлагает встроенную поддержку XML и
// XML-подобных форматов с пакетом `encoding.xml`.
package main
@ -8,13 +8,12 @@ import (
"fmt"
)
// This type will be mapped to XML. Similarly to the
// JSON examples, field tags contain directives for the
// encoder and decoder. Here we use some special features
// of the XML package: the `XMLName` field name dictates
// the name of the XML element representing this struct;
// `id,attr` means that the `Id` field is an XML
// _attribute_ rather than a nested element.
// Этот тип будет сопоставлен с XML. Как и в примерах JSON,
// теги полей содержат директивы для кодера и декодера.
// Здесь мы используем некоторые особенности пакета XML:
// `XMLName` определяет имя элемента XML, представляющего
// эту структуру; `id,attr` означает, что поле `Id` является
// _атрибутом_ XML, а не вложенным элементом.
type Plant struct {
XMLName xml.Name `xml:"plant"`
Id int `xml:"id,attr"`
@ -31,20 +30,20 @@ func main() {
coffee := &Plant{Id: 27, Name: "Coffee"}
coffee.Origin = []string{"Ethiopia", "Brazil"}
// Emit XML representing our plant; using
// `MarshalIndent` to produce a more
// human-readable output.
// Создаем XML, представляющий наш `plant`;
// использование `MarshalIndent` для создания более
// читабельного вывода.
out, _ := xml.MarshalIndent(coffee, " ", " ")
fmt.Println(string(out))
// To add a generic XML header to the output, append
// it explicitly.
// Чтобы добавить общий заголовок XML к выводу, добавьте
// его явно.
fmt.Println(xml.Header + string(out))
// Use `Unmarhshal` to parse a stream of bytes with XML
// into a data structure. If the XML is malformed or
// cannot be mapped onto Plant, a descriptive error
// will be returned.
// Используйте `Unmarhshal` для парсинга байтов с XML в
// структуру данных. Если XML имеет неправильный формат
// или не может быть преобразован в Plant, будет
// возвращена описательная ошибка.
var p Plant
if err := xml.Unmarshal(out, &p); err != nil {
panic(err)
@ -54,8 +53,9 @@ func main() {
tomato := &Plant{Id: 81, Name: "Tomato"}
tomato.Origin = []string{"Mexico", "California"}
// The `parent>child>plant` field tag tells the encoder
// to nest all `plant`s under `<parent><child>...`
// Поле `parent>child>plant` сообщает кодировщику о
// необходимости вложения всех `plant` в
// `<parent><child>...`
type Nesting struct {
XMLName xml.Name `xml:"nesting"`
Plants []*Plant `xml:"parent>child>plant"`