• 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)
    }
  • 相关阅读:
    C# 中类重写 ToString 方法
    虚方法(virtual)和抽象方法(abstract)的区别
    C#的扩展方法学习
    C# .NET 和.NET Framework区别
    C#值类型和引用类型
    抽象和接口的区别和使用
    什么是委托?
    什么是继承?
    设计模式:单一职责原则
    Java 13,最新最全新特性解读
  • 原文地址:https://www.cnblogs.com/pu369/p/10460490.html
Copyright © 2020-2023  润新知