问题描述:

I have the next XML file:

<separator colspan="4" string="Application"/>

<field name="sel_groups_9_28_10" modifiers="{}"/>

<newline/>

<field name="sel_groups_49_50" modifiers="{}"/>

<newline/>

<field name="sel_groups_68" modifiers="{}"/>

<newline/>

<field name="sel_groups_36_37" modifiers="{}"/>

<newline/>

<field name="sel_groups_21_22_23" modifiers="{}"/>

<newline/>

<field name="sel_groups_43_44" modifiers="{}"/>

<newline/>

<field name="sel_groups_5_57_58" modifiers="{}"/>

<newline/>

<field name="sel_groups_59_60" modifiers="{}"/>

<newline/>

<field name="sel_groups_61_62" modifiers="{}"/>

<newline/>

<field name="sel_groups_19" modifiers="{}"/>

<newline/>

<field name="sel_groups_3_4" modifiers="{}"/>

<newline/>

<separator colspan="4" string="MY GROUP"/>

<field name="in_group_144" modifiers="{}"/>

<field name="in_group_142" modifiers="{}"/>

<field name="in_group_148" modifiers="{}"/>

<field name="in_group_147" modifiers="{}"/>

<field name="in_group_146" modifiers="{}"/>

<field name="in_group_145" modifiers="{}"/>

<field name="in_group_141" modifiers="{}"/>

<field name="in_group_143" modifiers="{}"/>

<separator colspan="4" string="Technical configuration"/>

<field name="in_group_30" modifiers="{}"/>

<field name="in_group_46" modifiers="{}"/>

<field name="in_group_12" modifiers="{}"/>

<field name="in_group_45" modifiers="{}"/>

<field name="in_group_33" modifiers="{}"/>

<field name="in_group_66" modifiers="{}"/>

<field name="in_group_25" modifiers="{}"/>

<field name="in_group_32" modifiers="{}"/>

The common structure of the tree is:

<separator 1/>

<field 1/>

<field 2/>

<field N/>

<separator 2/>

<field 1/>

<field 2/>

<field N/>

<separator N/>

<field 1/>

<field 2/>

<field N/>

What I want is to get the separators whose string is different from MY GROUP and from all the following fields until the next separator (My purpose is to make every element invisible except for the separator MY GROUP and the fields in_group_144, in_group_142, in_group_148, in_group_147, in_group_146, in_group_145, in_group_141 and in_group_143).

The XML tree will vary its field names, so get the fields by their names will not be a solution.

Here lxml/Python : get previous-sibling gives how to get the previous sibling, but how could I get the previous sibling whose tag is separator in an efficient way?

My current solution:

def get_previous_separator(self, element):

previous_element = element.getprevious()

if previous_element.tag == 'separator':

return previous_element

else:

return get_previous_separator(element)

for element in tree:

if self.get_previous_separator(element).string != 'MY GROUP':

MAKE ELEMENT INVISIBLE

Is there any way more direct than a recursive method to manage my target?

网友答案:

You can use simple XPath to get the nearest preceding sibling separator element from current element :

element.xpath('preceding-sibling::separator[1]')
相关阅读:
Top