MST

星途 面试题库

面试题:Go中xml包处理命名空间:基础应用

在Go语言中,使用`encoding/xml`包处理包含命名空间的XML文档。给定如下XML片段:`<root xmlns:ns='http://example.com'><ns:child>content</ns:child></root>`,请编写Go代码将其解析到结构体中,并正确处理命名空间。
49.0万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
package main

import (
    "encoding/xml"
    "fmt"
)

// 定义结构体,注意标签中处理命名空间
type Root struct {
    XMLName xml.Name `xml:"root"`
    Child   Child    `xml:"ns:child"`
}

type Child struct {
    XMLName xml.Name
    Content string `xml:",chardata"`
}

func main() {
    xmlData := `<root xmlns:ns='http://example.com'><ns:child>content</ns:child></root>`
    var root Root
    err := xml.Unmarshal([]byte(xmlData), &root)
    if err != nil {
        fmt.Printf("解析错误: %v", err)
        return
    }
    fmt.Printf("解析结果: %+v\n", root)
}