使用 Python,当同级元素的标签是我要查找的字符串时,如何获取 XML 元素的文本?



我希望这是一个简单的问题。我会努力清楚地表明我正在努力实现的目标。下面只是我的XML文件的一小部分。我想做的是看看元素结构是否存在。如果是,代码继续。然后,我尝试查看所有元素,如果子元素(test)为False,那么我想获得id元素的文本。如果元素在元素之前,那么下面的代码将起作用。我想确保无论订单ID在中列出(在之前或之后),我都会得到属于相应父级的相应子ID。目前我正在使用元素树。

<data>
<cs>
<c>
<id>1</id>
<test>True</test>
<test2>False</test2>
<test3>False</test3>
<test4>True</test4>
</c>
<c>
<test>False</test>
<test2>False</test2>
<test3>False</test3>
<id>2</id>
<test4>True</test4>
</c>
</cs>

elementTree = self.param2
isCS = elementTree.find('./cs')
getCS = elementTree.findall('./cs')
CIDs = []
if isCS is None:
raise Exception("Unable to find the 'cs' element structure under <data>. Failed to build a list of CID's.")
else:
# Build the list of CID's.
for cs in getCS:
for c in cs:
for child in c.getchildren():
if str(child.tag).lower() == 'id':
myid = child.text
elif str(child.tag).lower() == 'test' and str(child.text).lower() == 'false':
CIDs.append(myid)
print CIDs

我得到的(取决于元素列出的顺序)是以下输出:

1

当我真的期待以下:

2

我只需要知道如何对的子元素运行特定的测试,并根据在的文本中找到的内容获取数据。

这里有一种方法:

cids = []
for c_node in tree.findall('.//cs/c'):
test_node = c_node.find('test')
if test_node is not None and test_node.text == 'False':
id_node = c_node.find('id')
cids.append(id_node.text)
print cids

讨论

  • for循环中,我定位cs下的所有c节点
  • 接下来,我检查了"test"节点是否存在并且为False
  • 最后,我将id附加到列表中

未测试。

# Build the list of CID's.
for cs in getCS:
for c in cs:
myid = None
mytest = None
for child in c.getchildren():
if str(child.tag).lower() == 'id':
myid = child.text
elif str(child.tag).lower() == 'test' and str(child.text).lower() == 'false':
mytest = True
if myid and mytest:
CIDs.append(myid)
print CIDs

也许它可以用不同的方式来实现——在c元素上使用一些特殊的函数或find()findall()


编辑:

lxml的示例(这是唯一的示例,因此它不是"防弹"的)

import lxml.etree
xml = '''<data>
<cs>
<c>
<id>1</id>
<test>True</test>
<test2>False</test2>
<test3>False</test3>
<test4>True</test4>
</c>
<c>
<test>False</test>
<test2>False</test2>
<test3>False</test3>
<id>2</id>
<test4>True</test4>
</c>
</cs>
</data>'''
tree = lxml.etree.fromstring(xml)
all_c = tree.findall('./cs/c')
#print all_c
results = []
for c in all_c:
#print c
myid = c.find('id').text
mytest = (c.find('test').text.lower() == 'false')
print myid, mytest
if myid and mytest: 
results.append(myid)
print "results:", results   

最新更新