2017-07-24 9 views
0

我的代碼(Python3)應該打印COLOR:Red│。當我運行它時,它不會給我一個錯誤消息,它不會打印任何東西。這裏是我的代碼和下面是XML文件,其中的數據所在位置:程序無法找到文件中的xml數據

import os, csv 
from xml.etree import ElementTree 

file_name = 'data.xml' 
full_file = os.path.abspath(os.path.join('xml', file_name)) 
dom = ElementTree.parse(full_file) 

attri = dom.findall('attribute') 
lst = [] 

for c in attri: 
    name = c.find('name').text 
    value = c.find('value').text 
    lst = (name + ':' + value) 
    print(lst, end = "│") 



<?xml version="1.0"?> 
<all> 
<items> 
<item> 
<attributes> 
<attribute> 
<name>COLOR</name> 
<value>Red</value> 
</attributes> 
</attribute> 
</item> 
</items> 
</all> 
+0

ups,我明白了。這不是我的代碼。在原始文件中它正確地爲 – Alexander

+0

假設XML是固定的,您需要首先獲取'all'標籤,然後是'items',然後是'item',然後是'attributes',然後最後找到其中的所有「屬性」標籤以打印每個的名稱/值。 'findall()'只搜索當前所選節點的直接子節點。 – zwer

回答

1

attri = dom.findall('attribute')正在返回任何結果。

的文檔的標題Finding interesting elements注意到

Element.findall()發現僅與一標籤,其是當前元素的直接子元素的部分。

但是

更復雜的規範哪些元素來尋找利用XPath是可能的。

最簡單的解決將是你的代碼更改

for c in dom.findall('.//attribute'): 
    name = c.find('.//name').text 
    value = c.find('.//value').text 
    print(name + ':' + value, end="│") 

更多信息請參見Supported XPath syntax

相關問題