java - 如何使用lxml更改android xml文件中的属性值,例如 "android:text"

标签 java android python lxml

我想使用 lxml 更改 android xml 文件的一些属性值。

例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <TextView android:id="@+id/version_label"
              android:layout_marginLeft="5sp"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="version"/>
</LinearLayout>

我想改变“android:text”的值,但是

textViewTagNode.attrib['android:text'] = "new value" 

没办法,也没办法

textViewTagNode.set('android:text', 'new value')

可以工作。我得到的只是“无效的属性名称 u'android:text'”

我知道这是命名空间问题,但我不知道如何解决。

非常感谢。

最佳答案

你的 key 不是'android:text'而是'{http://schemas.android.com/apk/res/android}text'

In [23]: s = '''<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">
    <TextView android:id="@+id/version_label"
              android:layout_marginLeft="5sp"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:text="version"/> </LinearLayout>'''

In [24]: tree = etree.XML(s)                                          


In [25]: c = tree.getchildren()[0]

In [26]: c.items()
Out[26]:  [('{http://schemas.android.com/apk/res/android}id', '@+id/version_label'),  ('{http://schemas.android.com/apk/res/android}layout_marginLeft', '5sp'),  ('{http://schemas.android.com/apk/res/android}layout_width', 'fill_parent'),  ('{http://schemas.android.com/apk/res/android}layout_height', 'wrap_content'),  ('{http://schemas.android.com/apk/res/android}text', 'version')]

关于java - 如何使用lxml更改android xml文件中的属性值,例如 "android:text",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13301280/

相关文章:

java - 从 Java 调用 Scala 泛型方法

java - CouchBase 与 Memcached 混合,失去了大多数 CouchDB 理念和功能?

python - 在 Python 中打开 JPEG 图像

python - 查找两个排序数组的中位数。是否可以消除一些不平等检查?

java - jOOQ - jOOQ 支持定义文件或 SQL 创建脚本的创建吗?

java - 如何在 Android MediaController 中实现快进/快退按钮的事件监听器

java - 如何使用联合运算符连接 sql 查询

java - 使用 HTTPClient 在 android 中发送 HTTPS post 请求以获得未验证的证书

android - 生成 JavaDocs Android Studio

android - 如果我已经为我的应用程序提供了 Android 许可,我是否应该对我的应用程序进行复制保护?