[英]Reading child objects using xmltree in python
XML 正文 (response.content)
<MediaPropertiesLayout>
<header>
<entry>
<displayName>Q</displayName>
<mediaProperty>callVariable1</mediaProperty>
<showInPopOver>false</showInPopOver>
</entry>
</header>
<column>
<entry>
<displayName>CallType</displayName>
<mediaProperty>callVariable1</mediaProperty>
<showInPopOver>true</showInPopOver>
</entry>
</column>
<column>
<entry>
<displayName>QueueName</displayName>
<mediaProperty>callVariable2</mediaProperty>
<showInPopOver>true</showInPopOver>
</entry>
</column>
<uri>/finesse/api/MediaPropertiesLayout/2</uri>
<name>CallTest</name>
<description>Test Variable</description>
<type>CUSTOM</type>
</MediaPropertiesLayout>
我正在嘗試從上面的 boxy 讀取子對象 (./column/entry/),這是來自服務器的 GET 響應。
O/pi 需要是
CallType
callVariable1
true
Left
callVariable2
false
<Space>
QueueName
callVariable2
true
Right
callVariable4
false
但是,我在沒有空間的情況下獲得了所需的 o/p。 空間的原因是我可以在 Excel 工作簿的不同列中填充第二個孩子。
CallType
callVariable1
true
Left
callVariable2
false
QueueName
callVariable2
true
Right
callVariable4
false
subroot= ET.fromstring(response.content)
for subchild in subroot.findall('./column/entry/'):
print(subchild.text)
謝謝森蒂爾
而不是使用findall() ,實現此目的的一種方法是使用 xml.etree iter()函數https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree .Element.iter
iter()將幫助您將每個單獨的<entry>
子子項作為單獨的對象。 然后您可以遍歷這些對象並在每個對象之后放置一個新行(或在您的情況下調用它的空格)。 代碼看起來像這樣:
subroot = ET.fromstring(response_content) # read from a string variable
for entry in subroot.iter('column'):
[print(entry[0][i].text) for i in range(len(entry[0]))]
print("\n") # any special character you want to print after each object
上面代碼的預期輸出:
CallType
callVariable1
true
QueueName
callVariable2
true
假設:每個<entry>
子子節點具有相同數量的子子節點
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.