首页 > 开发 > Python > 正文

python 解析xml中 attr 出现冒号的问题

2017-09-06 19:23:20  来源:网友分享
temps='''<application android:tempallowBackup="true" ></application>'''DOMTree = xml.dom.minidom.parseString(temps)print DOMTree代码如上,一旦出现 android: 解析就会出现异常。异常信息如下Traceback (most recent call last):  File "c:\Users\zzy\Desktop\python\temp.py", line 16, in <module>    DOMTree = xml.dom.minidom.parseString(temps)  File "C:\Python27\lib\xml\dom\minidom.py", line 1928, in parseString    return expatbuilder.parseString(string)  File "C:\Python27\lib\xml\dom\expatbuilder.py", line 940, in parseString    return builder.parseString(string)  File "C:\Python27\lib\xml\dom\expatbuilder.py", line 223, in parseString    parser.Parse(string, True)ExpatError: not well-formed (invalid token): line 2, column 14

解决方案

一个XML元素可以包含字母、数字以及其它一些可见字符,但必须遵守下面的一些规范:

  • 区分大小写,例如,<P>和<p>是两个不同的标记。

  • 不能以数字或"_" (下划线)开头。

  • 不能以xml(或XML、或Xml 等)开头。

  • 不能包含空格。

  • 名称中间不能包含冒号(:)


可以把冒号(:)先替换成别的合法字符,然后再解析。


更新

需要定义 命名空间xmlns:android="android"

import xml.etree.ElementTree as ETtmp = '''<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" />'''    d =ET.fromstring(tmp)print(d.keys())

结果:

['{android}layout_width', '{android}orientation', '{android}layout_height']