golang 解析XML


用adb操控android手機時,可以解析頁面控件信息(xml)

代碼如下:

package main

import (
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "os"
    "os/exec"
)

func main() {

    AdbShellUiautomatorDump()
    DecodeXML()
}

/*
//adb shell uiautomator dump /sdcard/ui.xml
獲取當前應用屏幕上所有控件的信息並保存在sdcard下ui.xml文件里面. sdk版本16以上
然后可以在電腦上解析該XML,根據其中的bounds找到控件坐標點,然后tap
可參考:
//https://blog.csdn.net/henni_719/article/details/72953251
//https://studygolang.com/articles/5328
*/
func AdbShellUiautomatorDump() {
    exec.Command("adb", "shell", "uiautomator", "dump", "--compressed", "/sdcard/window_dump.xml").Run()
    exec.Command("adb", "pull", "/sdcard/window_dump.xml", ".").Run()
    exec.Command("adb", "shell", "rm", "/sdcard/window_dump.xml").Run()
}

type HierarchyItem struct {
    XMLName xml.Name   `xml:"hierarchy"`
    Node    []NodeItem `xml:"node"`
    //Description string   `xml:",innerxml"`
}

//嵌套了自身,參考:https://studygolang.com/articles/3670
type NodeItem struct {
    XMLName     xml.Name   `xml:"node"`
    Node        []NodeItem `xml:"node"`
    Bounds      string     `xml:"bounds,attr"`
    Description string     `xml:",innerxml"`
}

func DecodeXML() {
    file, err := os.Open("window_dump.xml") // For read access.
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    defer file.Close()
    data, err := ioutil.ReadAll(file)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    v := HierarchyItem{}
    err = xml.Unmarshal(data, &v)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }

    fmt.Printf("v is: %+v", v.Node[0].Node[0].Node[0].Node[0].Node[0].Bounds)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM