![](/img/trans.png)
[英]Why am I not getting the text in the XML tag? - python elementtree
[英]Getting the last tag in ElementTree and append text
我有一些具有以下結構的XML:
<root>
<parent-1>
<text>blah-1</text>
<properties>
<property type="R" id="0005">text-value-A</property>
<property type="W" id="0003">text-value-B</property>
<property type="H" id="0002">text-value-C</property>
<property type="W" id="0008">text-value-D</property>
</properties>
</parent-1>
<parent-2>
<text>blah-2</text>
<properties>
<property type="W" id="0004">text-value-A</property>
<property type="H" id="0087">text-value-B</property>
</properties>
</parent-2>
<parent-3>
<text>blah-3</text>
<properties>
<property type="H" id="0087">text-value-C</property>
<property type="R" id="0008">text-value-A</property>
</properties>
</parent-3>
<parent-4>
<text>blah-4</text>
<properties>
<property type="H" id="0019">text-value-C</property>
<property type="R" id="0060">text-value-A</property>
</properties>
</parent-4>
</root>
目前,我正在解析text-value-
並將它們與一些字符串連接起來!
,但對於在屬性級別中最后出現的text-value-X
,我需要分配一些其他字符串&
,並輸出如下內容: text-value-A!text-value-B!text-value-C!text-value-D&text-value-A!text-value-B&text-value-C!text-value-A
由於<property
不能特定於標簽/具有隨機值,因此諸如if(item.text == 'text-value-A') #get text-value-A of parent-3
將不起作用。
我沒有保留重復的text-value-
(在這種情況下將不需要parent-4
因為parent-3
text-value-
相同),並且我想保留順序,因此enumerate
一下,我正在執行以下操作:
alist = []
for item in root.findall('parent/properties/property'):
alist.append(item.text)
self.alist = '!'.join([a for b,a in enumerate(alist) if a not in alist[:b]]
給定上面期望的輸出,我想知道是否需要針對此問題的其他方法,或者類似以下內容的概念將以某種方式起作用:
alist = []
for item in root.findall('parent/properties/property'):
alist.append(item.text)
for element in alist:
if element in alist[-1]:
self.alist = '&'.join([a for b,a in enumerate(alist) if a not in alist[:b]]
if not element in alist[-1]:
self.alist = '!'.join([a for b,a in enumerate(alist) if a not in alist[:b]]
謝謝
這可能就是您想要的。
property_texts
將包含每個文本的列表。 any
謂詞用於測試當前屬性的文本集是否已經被查看過。 如果不是,則將這些文本作為列表添加到集合中。 (使用set
邏輯以避免丟失不同順序的重復集合非常重要。) from xml.etree import ElementTree
tree = ElementTree.parse('bt123.xml')
property_text_lists = []
for properties in tree.findall('.//properties'):
property_texts = [p.text for p in properties]
if any([set(property_texts)==set(ptl) for ptl in property_text_lists]):
break
property_text_lists.append(property_texts)
print ('&'.join(['!'.join(property_text_lists[i]) for i in range(len(property_text_lists))]))
它確實產生此輸出。
text-value-A!text-value-B!text-value-C!text-value-D&text-value-A!text-value-B&text-value-C!text-value-A
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.