Groovy使用XmlSlurper解析XML文件

public class BytecodeFixPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        println "this is my custom plugin ModifyPlugin"
        //AppExtension就是build.gradle中android{...}这一块
        def android = project.extensions.getByType(AppExtension)
        //生产一个类
        if (project.plugins.hasPlugin(AppPlugin)) {
                android.applicationVariants.all { variant ->
                variant.outputs.all { output ->
                    output.processResources.doFirst { pm ->
                        String manifestPath = output.processResources.manifestFile
                        println "=====test manifestPath=====$manifestPath"
                        File file = new File(manifestPath)
                        println "=====test manifestPath file =====" + file.getText();
                        def manifestContent = file.getText()
                        manifestContent = manifestContent.replace('<uses-permission android:name="android.permission.BLUETOOTH" />', '')
                        def xml = new XmlSlurper().parseText(manifestContent)
                        xml.declareNamespace('android':'http://schemas.android.com/apk/res/android')
                        println xml.application[0].@"android:name"
                        xml.application[0]."activity".each{
                            println it."@android:name"
                            println "1" + it.'intent-filter'."@action".text()
                            println "2" + it.'intent-filter'."@action"
                            it."intent-filter".each{
                                filter -> println "3 " + filter.action."@android:name" + filter.category."@android:name"
                            }
//                            println "3" + it.intent-filter."@action"   //error
                        }
                        def res = xml.application.activity.find{it."intent-filter".find{filter -> return filter.action.find{filter.action.find{it.'@android:name'.text() == 'android.intent.action.MAIN' }} && filter.category.find{it.'@android:name'.text() == 'android.intent.category.LAUNCHER'}}}.'@android:name'
                        println res.text() + "======"
                        println "=====test xml=====$xml"

                    }
                }
            }
        }
//        project.android.registerTransform(new BytecodeFixTransform(project))
    }
}

注意事项:
1、节点的属性需要遍历;
2、可以直接用节点名称定位节点;
参考文章:
Groovy操作XML:https://www.twblogs.net/a/5ca11c9bbd9eee5b1a06a2b2
Groovy获取开机启动Activity:https://stackoverflow.com/questions/22979277/gradle-how-to-get-values-from-androidmanifest?rq=1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容