Python XML 解析器破坏 AndroidManifest.xml

2024-10-01 11:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图分析AndroidManifest.xml文件,以便在构建时以编程方式更改其某些值。(使用xml.dom.minidom)在

不幸的是,解析器会抛出格式错误的XML(即使我没有对从XML输入构建的DOM进行任何更改)

这里有一个非常简单的AndroidManifest.xml在

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.npike.android.sampleapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="net.npike.android.sampleapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

下面是我的非常简单的python脚本,它只需加载文件,对其进行解析,然后将其写回:

^{pr2}$

不幸的是,在上面共享的AndroidManifest上运行脚本后,以下输出将写入磁盘:

<?xml version="1.0" ?><manifest android:versionCode="1" android:versionName="1.0" package="net.npike.android.sampleapp" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17"/>

    <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:label="@string/app_name" android:name="net.npike.android.sampleapp.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>tent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是怎么回事?有没有更好的方法来解析Python中的AndroidManifest?在

编辑:我应该补充一下,格式错误的部分就是第一个标记之后的所有内容。在


Tags: namestringnetapplicationxmlactivityfilterlabel
2条回答

看起来这是因为输出比输入短,所以不会覆盖整个内容。在

试着写另一个文件?在

如果要用Python解析XML,只需使用etree

import xml.etree.ElementTree as etree

etree.register_namespace('android', 'http://schemas.android.com/apk/res/android')

with open('AndroidManifest.xml', 'r') as handle:
    root = etree.parse(handle)

root.find('application').set('android:allowBackup', 'false')
root.write('parsed.xml', encoding='utf-8', xml_declaration=True)

语法是可以理解的,它包含在标准库中,并且可以工作。在

相关问题 更多 >