【发布时间】:2014-09-24 01:32:06
【问题描述】:
这是Modify a XML using ElementTree的后续问题
我现在在我的 XML 中有命名空间,并尝试在 Parsing XML with namespace in Python via 'ElementTree' 上理解答案并获得以下信息。
XML 文件。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<grandParent>
<parent>
<child>Sam/Astronaut</child>
</parent>
</grandParent>
</project>
查看Parsing XML with namespace in Python via 'ElementTree'后我的python代码
import xml.etree.ElementTree as ET
spaces='xmlns':'http://maven.apache.org/POM/4.0.0','schemaLocation':'http://maven.apache.org/xsd/maven-4.0.0.xsd'}
tree = ET.parse("test.xml")
a=tree.find('parent')
for b in a.findall('child', namespaces=spaces):
if b.text.strip()=='Jay/Doctor':
print "child exists"
break
else:
ET.SubElement(a,'child').text="Jay/Doctor"
tree.write("test.xml")
我得到错误: AttributeError: 'NoneType' 对象没有属性 'findall'
【问题讨论】:
-
您发布的代码 sn-ps 都不是有效的 Python。第一个有杂散的 XML,两个都有混乱的缩进,第二个是缺少括号。
-
是的,我的错。我现在试着纠正它。
-
旁白:
else的缩进不正确。它想与for对齐,而不是与if。
标签: python xml lxml elementtree celementtree