golang读xml

发布时间:2024-07-05 01:04:10

XML(eXtensible Markup Language)是一种用于存储和传输数据的标记语言,它具有良好的可读性和可扩展性。在Golang中,我们可以使用标准库包中的"encoding/xml"来处理XML数据。本文将介绍如何使用golang读取和写入XML文件。

读取XML文件

要读取XML文件,我们需要先创建一个结构体类型,用于表示XML文件的结构。结构体的字段应与XML文件中的标签对应。

下面是一个示例的XML文件,我们将用它作为本文的示例:

```xml Everyday Italian Giada De Laurentiis 2005 30.00 Harry Potter J.K. Rowling 2005 29.99 ... ```

我们可以创建以下的结构体类型:

```go type Book struct { Category string `xml:"category,attr"` Title string `xml:"title"` Author string `xml:"author"` Year int `xml:"year"` Price float64 `xml:"price"` } type Bookstore struct { XMLName xml.Name `xml:"bookstore"` Books []Book `xml:"book"` } ```

解析XML文件

要解析XML文件,我们可以使用`xml.Unmarshal()`函数。

首先,我们需要打开XML文件:

```go file, err := os.Open("books.xml") if err != nil { fmt.Println("Failed to open XML file:", err) return } defer file.Close() ```

然后,我们可以创建一个Bookstore对象,用于存储从XML文件中解析出来的数据:

```go var bookstore Bookstore ```

最后,我们使用`xml.Unmarshal()`函数将XML文件解析为Bookstore对象:

```go err = xml.Unmarshal(file, &bookstore) if err != nil { fmt.Println("Failed to parse XML:", err) return } ```

现在,我们就可以访问Bookstore对象中的数据了:

```go for _, book := range bookstore.Books { fmt.Println("Category:", book.Category) fmt.Println("Title:", book.Title) fmt.Println("Author:", book.Author) fmt.Println("Year:", book.Year) fmt.Println("Price:", book.Price) fmt.Println() } ```

上面的代码将输出类似以下内容:

``` Category: cooking Title: Everyday Italian Author: Giada De Laurentiis Year: 2005 Price: 30.00 Category: children Title: Harry Potter Author: J.K. Rowling Year: 2005 Price: 29.99 ```

写入XML文件

要写入XML文件,我们可以使用`xml.MarshalIndent()`函数将数据序列化为XML格式,并指定缩进。

首先,我们创建一个包含要写入XML文件的数据的Bookstore对象:

```go bookstore := Bookstore{ Books: []Book{ { Category: "cooking", Title: "Everyday Italian", Author: "Giada De Laurentiis", Year: 2005, Price: 30.00, }, { Category: "children", Title: "Harry Potter", Author: "J.K. Rowling", Year: 2005, Price: 29.99, }, }, } ```

然后,我们可以使用`xml.MarshalIndent()`函数将Bookstore对象序列化为XML格式:

```go output, err := xml.MarshalIndent(bookstore, "", " ") if err != nil { fmt.Println("Failed to serialize to XML:", err) return } ```

最后,我们可以将生成的XML数据写入一个文件中:

```go err = ioutil.WriteFile("output.xml", output, 0644) if err != nil { fmt.Println("Failed to write XML file:", err) return } ```

现在,文件output.xml中将包含以下内容:

```xml Everyday Italian Giada De Laurentiis 2005 30.00 Harry Potter J.K. Rowling 2005 29.99 ```

通过上述的示例,我们可以看到使用golang读取和写入XML文件是相对简单的。无论是处理其他复杂的XML文件,还是将数据序列化为XML格式,Golang的标准库都提供了很好的支持。

相关推荐