[英]Extracting Specific Lines of XML with Python ElementTree
我對我正在做的使用 Python 的項目有點卡住了——我對這個項目很陌生。 有人告訴我使用 ElementTree 並從傳入的 XML 文件中獲取指定的數據。 這聽起來很簡單,但我不擅長編程。 下面是一個(非常!)傳入文件的小示例以及我嘗試使用的代碼。
我想要任何提示或下一步要去的地方。 我嘗試搜索並遵循其他人所做的操作,但似乎無法獲得相同的結果。 我的目標是獲取包含在“活動”、“房間”和“方向”中的信息,但稍后我將需要獲取更多信息。
我曾嘗試使用 XPath,但效果不佳,尤其是在 xml 使用的命名空間以及我需要的所有內容的 XPath 會變得太大的情況下。 我已經簡化了這個例子,所以我可以理解要做的原則,因為在此之后必須擴展它以從“AssetEquipment”和它們的多個實例中獲取更多信息。 然后最終目標是將來自一個設備的所有信息保存到字典中,以便我以后可以操作它,每個新設備都在自己單獨的字典中。
示例 XML:
<AssetData>
<Equipment>
<AssetEquipment ID="3" name="PC960">
<Active>Yes</Active>
<Location>
<RoomLocation>
<Room>23</Room>
<Area>
<X-Area>-1</X-Area>
<Y-Area>2.4</Y-Area>
</Area>
</RoomLocation>
</Location>
<Direction>Positive</Direction>
<AssetSupport>12</AssetSupport>
</AssetEquipment>
</Equipment>
示例代碼:
tree = ET.parse('C:\Temp\Example.xml')
root = tree.getroot()
ns = "{http://namespace.co.uk}"
for equipment in root.findall(ns + "Equipment//"):
tagname = re.sub(r'\{.*?\}','',equipment.tag)
name = equipment.get('name')
if tagname == 'AssetEquipment':
print "\tName: " + repr(name)
for attributes in root.findall(ns + "Equipment/" + ns + "AssetEquipment//"):
attname = re.sub(r'\{.*?\}','',attributes.tag)
if tagname == 'Room': #This does not work but I need it to be found while
#in this instance of "AssetEquipment" so it does not
#call information from another asset instead.
room = equipment.text
print "\t\tRoom:", repr(room)
import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
for elem in tree.getiterator():
if elem.tag=='{http://www.namespace.co.uk}AssetEquipment':
output={}
for elem1 in list(elem):
if elem1.tag=='{http://www.namespace.co.uk}Active':
output['Active']=elem1.text
if elem1.tag=='{http://www.namespace.co.uk}Direction':
output['Direction']=elem1.text
if elem1.tag=='{http://www.namespace.co.uk}Location':
for elem2 in list(elem1):
if elem2.tag=='{http://www.namespace.co.uk}RoomLocation':
for elem3 in list(elem2):
if elem3.tag=='{http://www.namespace.co.uk}Room':
output['Room']=elem3.text
print output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.