dongzhukuai8177 2014-06-13 18:30
浏览 91

Golang-仅解组特定的XML节点

I´m currently trying to learn golang by converting an existing project to "go". This involves working with XML data. The documentation about un-marshalling looks good so far, but I need only certain parts of the XML I´ve to process. The already existing project is using xpath and xslt to archive this. Unfortunately "go" doesn´t seem to have this.

The documentation has this as example:

package main

import (
    "encoding/xml"
    "fmt"
)

func main() {
type Email struct {
    Where string `xml:"where,attr"`
        Addr  string
    }
    type Address struct {
    City, State string
    }
    type Result struct {
    XMLName xml.Name `xml:"Person"`
        Name    string   `xml:"FullName"`
        Phone   string
        Email   []Email
        Groups  []string `xml:"Group>Value"`
        Address
    }
    v := Result{Name: "none", Phone: "none"}

    data := `
        <Person>
            <FullName>Grace R. Emlin</FullName>
            <Company>Example Inc.</Company>
            <Email where="home">
                <Addr>gre@example.com</Addr>
            </Email>
            <Email where='work'>
                <Addr>gre@work.com</Addr>
            </Email>
            <Group>
                <Value>Friends</Value>
                <Value>Squash</Value>
            </Group>
            <City>Hanga Roa</City>
            <State>Easter Island</State>
        </Person>
    `
    err := xml.Unmarshal([]byte(data), &v)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("XMLName: %#v
", v.XMLName)
    fmt.Printf("Name: %q
", v.Name)
    fmt.Printf("Phone: %q
", v.Phone)
    fmt.Printf("Email: %v
", v.Email)
    fmt.Printf("Groups: %v
", v.Groups)
    fmt.Printf("Address: %v
", v.Address)
}

How is it possible to filter on an attribute to get only the "home" Email Nodes (and child nodes, if they exist)? Something like

Email   []Email  `xml:"Email[@where='home']"`
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 Python3.5 相关代码写作
    • ¥20 测距传感器数据手册i2c
    • ¥15 RPA正常跑,cmd输入cookies跑不出来
    • ¥15 求帮我调试一下freefem代码
    • ¥15 matlab代码解决,怎么运行
    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)