Python XML解析器破坏AndroidManifest.xml

时间:2013-02-27 01:47:04

标签: android python

我正在尝试从Android项目解析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脚本,它只加载文件,解析它,然后将其写回:

#!/usr/bin/python
import os
from xml.dom.minidom import parse
dom1 = parse("AndroidManifest.xml")

f = os.open("AndroidManifest.xml", os.O_RDWR)
os.write( f, dom1.toxml() )

不幸的是,在上面共享的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?

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

2 个答案:

答案 0 :(得分:1)

如果要使用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)

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

答案 1 :(得分:0)

看起来这是因为输出比输入短,所以它不会覆盖整个事物。

尝试写出另一个文件?