登录
首页 >  Golang >  Go问答

从数据库中提取数据并在地图上展示

来源:stackoverflow

时间:2024-03-19 23:03:31 418浏览 收藏

通过利用 pathval 结构,该结构将路径和值组合在一起,我们可以创建树形结构,该结构可以灵活地表示来自不同数据库的层次化数据。然后,我们可以使用 XML 编码器将此树转换为 XML,从而使我们能够轻松地将数据可视化在地图上或以其他方式进行处理。

问题内容

问题是 - 我不想为每个数据库创建一个结构(如果我描述所有 xml 的所有结构,则代码太多,我有超过 200 个数据库)。所以我需要一些可以用于其中任何一个的东西

我的一个数据库的数据如下所示:

----------------------------------------------
id  |      path                          |value
-----------------------------------------------
1   | salesplan/salesplandata/year       | 2021
2   | salesplan/salesplandata/month      | july
3   | salesplan/salesplanperson/id       | 123
....
1700| salesplan/salesplarspot/spots/city | ny

我尝试了很多方法,但最终我无法创建一个灵活的映射结构,它可以在每个数据库行之后正确更新 下一个代码允许我存储所有最终标签,但我想在树上向上移动并更新洞结构

type ParentTag struct {
    Key   string
    Value []InnerTag
}

type InnerTag struct {
    Key   string
    Value string
}

func (s *ParentTag) Add(i InnerTag) {
    s.Value = append(s.Value, i)
    log.Printf("New X=%d", s.Value)
}

func main() {
    //xmlMap := Tag{}
    parentTagsStorage := []ParentTag{}

    house_1 := []string{"mydoc", "Country", "City", "Street", "House", "14"}
    house_2 := []string{"mydoc", "Country", "City", "Street", "House", "15"}
    street_1 := []string{"mydoc", "Country", "City", "Street", "Maddison"}
    city_1 := []string{"mydoc", "Country", "City", "NY"}

    allData := make([][]string, 0)
    allData = append(allData, house_1)
    allData = append(allData, house_2)
    allData = append(allData, street_1)
    allData = append(allData, city_1)


    for _, row := range allData {
        // the latest 2 elements present xml-tag and all previous ones are parents tags
        // 
        //    1
        // 
        innerTag := InnerTag{
            Key:   row[len(row)-2],
            Value: row[len(row)-1],
        }
        ifParentTagExist := false

        for i, pTag := range parentTagsStorage {
            if pTag.Key == row[len(row)-3] {
                pTag.Add(innerTag)
                parentTagsStorage[i] = pTag
                ifParentTagExist = true
            }
        }
        if !ifParentTagExist {
            parentTag := ParentTag{
                Key:   row[len(row)-3],
                Value: []InnerTag{innerTag},
            }
            parentTagsStorage = append(parentTagsStorage, parentTag)
        }
    }
}

如果有任何想法,我都会非常高兴


解决方案


好的,我们开始:

package main

import (
    "encoding/json"
    "encoding/xml"
    "fmt"
    "io"
    "os"
    "strings"
)

type pathval struct {
    path string
    val  interface{}
}

func encode(dst io.writer, src []pathval) error {
    enc := xml.newencoder(dst)
    enc.indent("", "\t") // for a prettier look

    tree := maketree(src)

    err := encodetree(enc, tree)
    if err != nil {
        return err
    }

    return enc.flush()
}

func encodetree(enc *xml.encoder, tree tree) error {
    for key, node := range tree {
        err := enc.encodetoken(xml.startelement{
            name: xml.name{
                local: key,
            },
        })
        if err != nil {
            return err
        }

        if node.subtree != nil {
            err = encodetree(enc, node.subtree)
            if err != nil {
                return err
            }
        }
        if node.value != nil {
            err = encodevalue(enc, node.value)
            if err != nil {
                return err
            }
        }

        err = enc.encodetoken(xml.endelement{
            name: xml.name{
                local: key,
            },
        })
        if err != nil {
            return err
        }
    }

    return nil
}

func encodevalue(enc *xml.encoder, val interface{}) error {
    return enc.encodetoken(xml.chardata(fmt.sprintf("%v", val)))
}

type tree map[string]*treenode

type treenode struct {
    subtree tree
    value   interface{}
}

func maketree(src []pathval) tree {
    root := make(tree)

    for _, elem := range src {
        comps := strings.split(elem.path, "/")
        comps, last := comps[:len(comps)-1], comps[len(comps)-1]

        subtree := root
        for _, comp := range comps {
            node, exists := subtree[comp]
            if !exists {
                newtree := make(tree)
                subtree[comp] = &treenode{
                    subtree: newtree,
                }
                subtree = newtree
                continue
            }
            if node.subtree == nil {
                node.subtree = make(tree)
            }
            subtree = node.subtree
        }

        if node, exists := subtree[last]; exists {
            node.value = elem.val
        } else {
            subtree[last] = &treenode{
                value: elem.val,
            }
        }
    }

    return root
}

// "table 1"
var data1 = []pathval{
    pathval{
        path: "salesplan/salesplandata/year",
        val:  2021,
    },
    pathval{
        path: "salesplan/salesplandata/month",
        val:  "july",
    },
    pathval{
        path: "salesplan/salesplandata/id",
        val:  123,
    },
    pathval{
        path: "salesplan/salesplanspot/spots/city",
        val:  "ny",
    },
}

// "table 2"
var data2 = []pathval{
    pathval{
        path: "mydoc/country/city/street/house",
        val:  14,
    },
    pathval{
        path: "mydoc/country/city/street/house",
        val:  15,
    },
    pathval{
        path: "mydoc/country/city/street",
        val:  "maddison",
    },
    pathval{
        path: "mydoc/country/city",
        val:  "ny",
    },
}

func main() {
    out, _ := json.marshalindent(maketree(data1), "", "\t")
    fmt.printf("%s\n", out)
    fmt.println(encode(os.stdout, data1))

    out, _ = json.marshalindent(maketree(data2), "", "\t")
    fmt.printf("%s\n", out)
    fmt.println(encode(os.stdout, data2))
}

Playground。)

在示例数据(嵌入到示例中的两个“表”作为 data1data2)上,我们得到


    
        123
        2021
        july
    
    
        
            ny
        
    


    
        
            
                15Maddison
            NY
        
    

分别。

请注意放置在 元素内的“maddison”和放置在 元素内的“ny”的那些“怪异”情况; 另请注意 14 的缺失。
我不知道如何准确处理这两个问题(如果它们是问题),因为您的问题没有明确说明有关处理它们的任何偏好。

我想说处理多个叶子元素相当简单 - 只需确保不要覆盖 maketree 中的 value ,而是提供收集多个值(可能收集在切片中)并在 encodetree 中说明这一点。
如何处理应包含“普通”值和嵌套元素的潜在 xml 元素的情况确实是一个悬而未决的问题:我所展示的是 100% 符合标准的 xml,但最终结果可能

不过,让我把这些留给读者作为练习。

请注意,该解决方案仅使用 encoding/json 包从输入数据中“转储”由 maketree 创建的树;算法的工作不需要它。

以上就是《从数据库中提取数据并在地图上展示》的详细内容,更多关于的资料请关注golang学习网公众号!

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