登录
首页 >  Golang >  Go问答

XML 数据的提取方法

来源:stackoverflow

时间:2024-02-12 11:48:16 266浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《XML 数据的提取方法》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我正在努力从 xml 输出中提取数据。 我写了下面的代码。我只需要从下面的 xml 中提取部门号。 运行以下代码时得到空输出。 有人可以告诉我如何从 xml 中提取部门编号以及为什么我得到 null 作为输出吗?

package main

import (
    "encoding/xml"
    "fmt"
)

type Users struct {
    XMLName xml.Name `xml:"users"`
    User   User   `xml:"user"`
}
type User struct {
    XMLName xml.Name `xml:"user"` 
    Type string  `xml:"name"` 
    DD  DD   `xml:"dd"`
}
type DD struct {
    XMLName xml.Name `xml:"dd"` 
    Number string  `xml:"number"`
    Description string  `xml:"description"` 
   Type  Type   `xml:"type"`
    Dept  Dept   `xml:"dept"`
}
type Type struct{
   XMLName xml.Name `xml:"type"` 
}
type Dept struct {
    XMLName xml.Name `xml:"dept"`
    Number string  `xml:"number"`
   Type  Type   `xml:"type"`
}

func main() {
var users Users
var byteValue = []byte(`<users>
<user>
<type>1</type>
<bu>
    <number>123</number>
    <id>100</id>
    <type>
        <code>123</code>
    </type>
</bu>
<dd>
    <number>1</number>
    <description>abc</description>
    <type>
        <code>12345</code>
        <id>qw123<id>
    <type>
    <dept>
        <number>10</number>      <<<<<<<
        <type>qw12345</type>
        
    </dept>
</dd>
<bd>
    <code>34we5</code>
    <id>qw123<id>
</bd>
<OD>
    <code>9876</code>
    <id>qwerty123<id>
</OD>   
</user>
</users>`)
xml.Unmarshal(byteValue, &users)
fmt.Println("Dept Number: " + users.User.DD.Dept.Number)
}

正确答案


看起来提供的 xml 是错误的。请尝试使用下面的 xml

<users>
    <user>
        <type>1</type>
        <bu>
            <number>123</number>
            <id>100</id>
            <type>
                <code>123</code>
            </type>
        </bu>
        <dd>
            <number>1</number>
            <description>abc</description>
            <type>
                <code>12345</code>
                <id>qw123</id>
            </type>
            <dept>
                <number>10</number>
                <type>qw12345</type>
            </dept>
        </dd>
        <bd>
            <code>34we5</code>
            <id>qw123</id>
        </bd>
        <OD>
            <code>9876</code>
            <id>qwerty123</id>
        </OD>
    </user>
</users>

您可以使用您在演示中提供的示例来查看工作示例。 https://play.golang.org/p/4zQsaz5Z_5P

到这里,我们也就讲完了《XML 数据的提取方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>