You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Handling text file is a big part of web development, we often need to produce or handle received text content, including strings, numbers, JSON, XML, etc. As a high performance language, Go has good support from standard library, and you'll find out that it's design just awesome, you can easily use them to deal with your text content. This chapter contains 4 sections, which gives full introduction of text processing in Go.
3
+
Manejo de archivo de texto es una parte importante del desarrollo web, a menudo necesitamos producir o manejar el contenido de texto recibidos, incluyendo palabras, números, JSON, XML, etc Como un lenguaje de alto rendimiento, Go tiene un buen apoyo de la biblioteca estándar, y usted hacer su diseño más que impresionante, se puede utilizar fácilmente para hacer frente a su contenido de texto. Este capítulo contiene 4 secciones, lo que da la plena introducción del tratamiento de textos en Go.
4
4
5
-
XML is an interactive language that is commonly used in many API, many web servers that are written by Java are using XML as standard interaction language, we will talk about XML in section 7.1. In section 7.2, we will take a look at JSON which is very popular in recent years and much more convenient than XML. In section 7.3, we are going to talk about regular expression which looks like a language that is used by aliens. In section 7.4, you will see how to use MVC model to develop applications in Go and use `template` package to use templates. In section 7.5, we'll give a introduction of operating files and folders. Finally, we will explain some string operations in Go in section 7.6.
5
+
XML es un lenguaje interactivo que se usan comúnmente en muchas API, muchos servidores web que se escriben en Java están utilizando XML como lenguaje de interacción estándar, vamos a hablar de XML en la sección 7.1. En la sección 7.2, vamos a echar un vistazo a JSON, que es muy popular en los últimos años y mucho más conveniente que el XML. En la sección 7.3, vamos a hablar de la expresión regular que se parece a un lenguaje que es utilizado por aliens. En la sección 7.4, verá cómo utilizar el modelo MVC para desarrollar aplicaciones en Go y el uso de la plantilla paquete para usar plantillas. En la sección 7.5, le daremos una introducción de archivos y carpetas de explotación. Por último, vamos a explicar algunas de las operaciones de cadena en Go en la sección 7.6.
Copy file name to clipboardExpand all lines: eBook/07.1.md
+58-52
Original file line number
Diff line number
Diff line change
@@ -1,10 +1,10 @@
1
1
# 7.1 XML
2
2
3
-
XML is a commonly used data communication format in web services today, it becomes more and more important role in daily development. In this section, we're going to introduce how to work with XML through standard library.
3
+
XML es un formato de comunicación de datos comúnmente utilizado en los servicios web hoy en día, se hace más y más importante el papel en el desarrollo diario. En esta sección, vamos a presentar la forma de trabajar con XML a través de la biblioteca estándar.
4
4
5
-
I'll not teach what is XML or something like that, please read more documentation about XML if you haven't known that. We only focus on how to encode and decode XML files.
5
+
Yo no voy a enseñar lo que es XML o algo así, por favor lea más documentación acerca de XML si no es sabido. Sólo nos centramos en cómo codificar y decodificar archivos XML.
6
6
7
-
Suppose you are a operation staff, and you have following XML configuration file:
7
+
Suponga que usted es un personal operación, y dispone de los siguientes archivos de configuración XML:
8
8
9
9
<?xml version="1.0" encoding="utf-8"?>
10
10
<servers version="1">
@@ -18,15 +18,17 @@ Suppose you are a operation staff, and you have following XML configuration file
18
18
</server>
19
19
</servers>
20
20
21
-
Above XML document contains two kinds of information about your server, which are server name and IP; we will use this document in our following examples.
21
+
este documento XML contiene dos tipos de información acerca de su servidor, que son el nombre del servidor y el IP; vamos a utilizar este documento en nuestras siguientes ejemplos.
22
22
23
-
## Parse XML
23
+
## Analizar XML
24
24
25
-
How to parse this XML document? We can use function`Unmarshal`in package`xml`to do this.
25
+
Cómo analizar este documento XML? Podemos utilizar la función`Unmarshal`del paquete`xml`para hacer esto.
26
26
27
27
func Unmarshal(data []byte, v interface{}) error
28
28
29
-
data receives data stream from XML, v is the structure you want to output, it is a interface, which means you can convert XML to any kind of structures. Here we only talk about how to convert to `struct` because they have similar tree structures.
29
+
data recibe la salida de datos de XML, v es la estructura que desea para la salida, que es una interfaz, lo que significa que puede convertir XML a cualquier tipo de estructuras. Aquí sólo hablamos acerca de cómo convertir a `struct` porque tienen estructuras de árboles similares.
30
+
31
+
Código de ejemplo:
30
32
31
33
Sample code:
32
34
@@ -74,7 +76,7 @@ Sample code:
74
76
fmt.Println(v)
75
77
}
76
78
77
-
XML actually is a tree data structure, and we can define a almost same struct in Go, then use `xml.Unmarshal`to convert from XML to our struct object. The sample code will print following content:
79
+
XML en realidad es una estructura de datos de árbol, y podemos definir casi una misma estructura en Go, a continuación, utilizar `xml.Unmarshal`para convertir de XML a nuestro objeto struct. El código de ejemplo imprimirá siguiente contenido:
@@ -87,43 +89,42 @@ XML actually is a tree data structure, and we can define a almost same struct in
87
89
</server>
88
90
}
89
91
90
-
We used `xml.Unmarshal`to parse XML document to corresponding struct object, and you should see that we have something like`xml:"serverName"`in our struct. This is a feature of struct which is called `struct tag`for helping reflection. Let's see the definition of `Unmarshal`again:
92
+
Utilizamos `xml.Unmarshal`para pasar el documento XML correspondiente a struct objeto, y usted debería ver que tenemos algo así como`xml:"serverName"`en nuestra estructura. Esta es una característica de la estructura que es llamada `struct tag`para ayudar a la reflexión. Veamos la definición de `Unmarshal`de nuevo:
91
93
92
94
func Unmarshal(data []byte, v interface{}) error
93
95
94
-
The first argument is XML data stream, the second argument is the type of storage, for now it supports struct, slice and string. XML package uses reflection to achieve data mapping, so all fields in v should be exported. But we still have a problem, how can it knows which field is corresponding to another one? Here is a priority level when parse data. It tries to find struct tag first, if it cannot find then get field name. Be aware that all tags, field name and XML element are case sensitive, so you have to make sure that one-one correspondence.
96
+
El primer argumento es la secuencia de datos XML, el segundo argumento es el tipo de almacenamiento, por ahora soporta struct, slice and string. El paquete XML utiliza la reflexión para lograr la asignación de datos, por lo que todos los campos de v debe ser exportado. Pero todavía tenemos un problema, ¿cómo puede sabe qué campo se corresponde con otro? Este es un nivel de prioridad cuando los datos de análisis sintáctico. Se trata de encontrar struct tag en primer lugar, si no se puede encontrar a continuación, obtener el nombre del campo. Tenga en cuenta que todas las etiquetas, el nombre del campo y el elemento XML distinguen entre mayúsculas y minúsculas, por lo que usted tiene que asegurarse de que la correspondencia uno a uno.
95
97
96
-
Go reflection mechanism allows you to use these tag information to reflect XML data to struct object. If you want to know more about reflection in Go, please read more about package documentation of struct tag and reflect.
98
+
El mecanismo reflexión de go le permite utilizar estos datos de la etiqueta para reflejar los datos XML a struct objeto. Si usted quiere saber más sobre la reflexión en Go, por favor, lea más acerca de la documentación del paquete de struct tag y reflect.
97
99
98
-
Here are the rules when package `xml` parse XML document to struct:
100
+
Aquí están las reglas al paquete xml documento de análisis sintáctico XML a struct:
99
101
100
-
-If the a field type is string or []byte with tag `",innerxml"`, `Unmarshal`assign raw XML data to it, like`Description`in above example:
102
+
-Si el tipo de campo es string or []byte with tag `",innerxml"`, `Unmarshal`asignar datos XML sin formato a ella, como`Description`en el ejemplo de arriba:
101
103
102
104
Shanghai_VPN127.0.0.1Beijing_VPN127.0.0.2
103
105
104
-
-If a field called `XMLName`and its type is`xml.Name`, then it gets element name, like `servers` in above example.
105
-
-If a field's tag contains corresponding element name, then it gets element name as well, like `servername` and `serverip`in above example.
106
-
-If a field's tag contains `",attr"`, then it gets corresponding element's attribute, like `version` in above example.
107
-
-If a field's tag contains something like `"a>b>c"`, it gets value of element c of node b of node a.
108
-
-If a field's tag contains `"="`, then it gets nothing.
109
-
-If a field's tag contains `",any"`, then it gets all child elements which do not fit other rules.
110
-
-If XML elements have one or more comments, all of these comments will be added to the first field that has the tag that contains `",comments"`, this field type can be string or []byte, if this kind field does not exist, all comments are discard.
106
+
-Si un campo llamado`XMLName`y su tipo es`xml.Name` , entonces se pone el nombre del elemento, como los servidores de ejemplo anterior.
107
+
-Si la etiqueta de un campo contiene el nombre del elemento correspondiente, entonces se pone el nombre del elemento, así como `servername` and `serverip`en el ejemplo anterior.
108
+
-Si la etiqueta de un campo contiene ", attr" , entonces se pone atributo correspondiente del elemento, al igual que la versión en el ejemplo anterior.
109
+
-Si la etiqueta de un campo contiene algo así como "a> b> c" , se obtiene el valor del elemento c de nodo b de nodo a.
110
+
-Si la etiqueta de un campo contiene "=" , luego se pone nada.
111
+
-Si la etiqueta de un campo contiene ", ninguna" , luego se pone todos los elementos secundarios que no se ajusten a otras normas.
112
+
-Si los elementos XML tienen uno o más comentarios, todos estos comentarios se agregará al primer campo que tiene la etiqueta que contiene `",comments"` , este tipo de campo puede ser de string or []byte, si este campo tipo no existe, todos los comentarios se descartan.
111
113
112
-
These rules tell you how to define tags in struct, once you understand these rules, everything as easy as the sample code. Because tags and XML elements are one-one correspondence, we can also use slice to represent multiple elements in same level.
114
+
Estas reglas indican cómo definir etiquetas de estructura, una vez que entienda estas reglas, todo tan fácil como el código de ejemplo. Dado que las etiquetas y los elementos XML son correspondencia uno a uno, también podemos utilizar la rebanada para representar múltiples elementos en un mismo nivel.
113
115
114
-
Note that all fields in struct should be exported(capitalize) in order to parse data correctly.
116
+
Tenga en cuenta que todos los campos de struct deben exportarse (capitalizar) con el fin de analizar los datos correctamente.
115
117
116
-
## Produce XML
118
+
## Producir XML
117
119
118
-
What if we want to produce XML document instead of parsing it, how can we do it in Go? `xml` package provides two functions which are`Marshal` and `MarshalIndent`where the second function has indents for your XML document. Their definition as follows:
120
+
¿Qué pasa si queremos producir el documento XML en lugar de analizarlo, ¿cómo podemos hacerlo en Go? xml paquete proporciona dos funciones que son`Marshal` and `MarshalIndent`donde la segunda función tiene guiones para el documento XML. Su definición de la siguiente manera:
The first argument is for storing XML data stream for both functions.
124
-
125
-
Let's has an example to see how it works:
125
+
El primer argumento es para almacenar la secuencia de datos XML para ambas funciones.
126
126
127
+
Vamos a tiene un ejemplo para ver cómo funciona:
127
128
package main
128
129
129
130
import (
@@ -156,7 +157,7 @@ Let's has an example to see how it works:
156
157
os.Stdout.Write(output)
157
158
}
158
159
159
-
The above example prints following information:
160
+
El ejemplo anterior imprime siguiente información:
160
161
161
162
<?xml version="1.0" encoding="UTF-8"?>
162
163
<servers version="1">
@@ -170,34 +171,39 @@ The above example prints following information:
170
171
</server>
171
172
</servers>
172
173
173
-
As we defined before, the reason we have `os.Stdout.Write([]byte(xml.Header))` is both of function `xml.MarshalIndent` and `xml.Marshal` do not output XML header by itself, so we have to print it in order to produce XML document correctly.
174
+
Como hemos definido antes, la razón que tenemos `os.Stdout.Write([]byte(xml.Header))` es a la vez de la función `xml.MarshalIndent` y `xml.Marshal` hacer cabecera XML no se emiten por sí mismo, así que tenemos que imprimirlo en orden para producir el documento XML correctamente.
175
+
176
+
Aquí vemos `Marshal` también recibe v en el tipo de `interface{}` , por lo que lo son las reglas cuando se produce el documento XML?
174
177
175
-
Here we see `Marshal` also receives v in type `interface{}`, so what are the rules when it produces XML document?
178
+
- Si v es un array or slice, imprime todos los elementos como el valor.
179
+
- Si v es un puntero, se imprime el contenido que v señale, imprime nada cuando v es nil.
180
+
- Si v es una interfaz, que lidiar con la interfaz también
181
+
- Si v es uno de otros tipos, se imprime valor de ese tipo.
176
182
177
-
- If v is a array or slice, it prints all elements like value.
178
-
- If v is a pointer, it prints content that v point to, it prints nothing when v is nil.
179
-
- If v is a interface, it deal with interface as well.
180
-
- If v is one of other types, it prints value of that type.
183
+
Así que ¿cómo puede decidir el nombre elementos "? De ello se sigue las reglas siguientes:
181
184
182
-
So how can it decide elements' name? It follows following rules:
183
185
184
-
- If v is a struct, it defines name in tag of XMLName.
185
-
- Field name is XMLName and type is xml.Name.
186
-
- Field tag in struct.
187
-
- Field name in struct.
188
-
- Type name of marshal.
186
+
Nombre de campo es XMLName y el tipo es xml.Name.
187
+
Etiqueta de campo en una estructura.
188
+
Nombre del campo en la estructura.
189
+
Escriba el nombre del mariscal.
190
+
- Si v es una estructura, que define el nombre en la etiqueta de XMLName.
191
+
- Nombre de campo es XMLName y el tipo es xml.Name.
192
+
- Etiqueta de campo en una estructura.
193
+
- Nombre del campo en la estructura.
194
+
- Nombre del Tipo de marshal.
189
195
190
-
Then we need to figure out how to set tags in order to produce final XML document.
196
+
Entonces tenemos que encontrar la manera de fijar las etiquetas de fin de producir documentos XML final.
191
197
192
-
- XMLName will not be printed.
193
-
-Fields that have tag contains `"-"` will not be printed.
194
-
-If tag contains `"name,attr"`, it uses name as attribute name and field value as value, like `version` in above example.
195
-
-If tag contains `",attr"`, it uses field's name as attribute name and field value as value.
196
-
-If tag contains `",chardata"`, it prints character data instead of element.
197
-
-If tag contains `",innerxml"`, it prints raw value.
198
-
-If tag contains `",comment"`, it prints it as comments without escaping, so you cannot have "--" in its value.
199
-
-If tag contains `"omitempty"`, it omits this field if its value is zero-value, including false, 0, nil pointer or nil interface, zero length of array, slice, map and string.
200
-
-If tag contains `"a>b>c"`, it prints three elements where a contains b, b contains c, like following code:
198
+
- XMLName no se imprimirán.
199
+
-Los campos que tienen etiqueta contiene "-" no se imprimirán.
200
+
-Si la etiqueta contiene`"name,attr"` , se utiliza el nombre como nombre de atributo y valor del campo como valor, al igual que la versión en el ejemplo anterior.
201
+
-Si la etiqueta contiene `",attr"`, utiliza el nombre del campo como nombre de atributo y valor del campo como valor.
202
+
-Si la etiqueta contiene `",chardata"`, imprime los datos de caracteres en lugar del elemento.
203
+
-Si la etiqueta contiene`",innerxml"`, imprime valor crudo.
204
+
-Si la etiqueta contiene`",comment"`, se lo imprime como comentarios sin escapar, por lo que no puede tener "-" en su valor.
205
+
-Si la etiqueta contiene `"omitempty"`, omite este campo si su valor es de valor cero, incluyendo falsa, 0, un puntero nulo o interfaz nula, longitud cero de la matriz, rebanada, el mapa y la cadena.
206
+
-Si la etiqueta contiene `"a>b>c"`, imprime tres elementos en los que A contiene b, b c contiene, al igual que el siguiente código:
201
207
202
208
FirstName string `xml:"name>first"`
203
209
LastName string `xml:"name>last"`
@@ -207,10 +213,10 @@ Then we need to figure out how to set tags in order to produce final XML documen
207
213
<last>Xie</last>
208
214
</name>
209
215
210
-
You may notice that struct tag is very useful when you deal with XML, as well as other data format in following sections, if you still have problems with working with struct tag, you probably should read more documentation about it before get into next section.
216
+
Usted puede notar que código struct es muy útil cuando se trabaja con XML, así como otro formato de datos en las secciones siguientes, si usted todavía tiene problemas con el trabajo con struct tag, probablemente debería leer más documentación al respecto antes de entrar en la siguiente sección.
0 commit comments