2016-07-01 3 views

ответ

5

Найти все целевые элементы (есть некоторые способы сделать это), а затем использовать встроенную функцию len(), чтобы получить счет. Например, если вы имеете в виду рассчитывать только прямые элементы Дитя корня:

from lxml import etree 
doc = etree.parse("file.xml") 
root = doc.getroot() 

result = len(root.getchildren()) 

или, если вы имеете в виду, чтобы сосчитать все элементы в пределах корневого элемента:

result = len(root.xpath(".//*")) 
+0

результат = LEN (root.xpath (".//*")) это то, что именно я ищу .. thank u, .. – mariz

+1

К сожалению, 'getchildren' был устаревшим в python 2.7. – ThomasW

1

Вам не нужно загружать все узлы в списке, вы можете использовать сумму и лениво перебирать:

from lxml import etree 
root = etree.parse(open("file.xml",'r')) 
count = sum(1 for _ in root.iter("*")) 
0

вы можете найти количество каждого элемента, как это:

from lxml import objectify 

file_root = objectify.parse('path/to/file').getroot() 
file_root.countchildren() # root's element count 
file_root.YourElementName.countchildren() # count of children in any element 
2

Другой способ получить количество подэлементов:

len(list(root)) 
0
# I used the len(list()) as a way to get the list of items in a feed, as I 
# copy more items I use the original len to break out of a for loop, otherwise 
# it would keep going as I add items. Thanks ThomasW for that code. 

import xml.etree.ElementTree as ET 

    def feedDoublePosts(xml_file, item_dup): 
     tree = ET.ElementTree(file=xml_file) 
     root = tree.getroot() 
     for a_post in tree.iter(item_dup): 
      goround = len(list(a_post)) 
      for post_children in a_post: 
       if post_children != a_post: 
       a_post.append(post_children) 
       goround -= 1 
       if goround == 0: 
        break 
     tree = ET.ElementTree(root) 
     with open("./data/updated.xml", "w") as f: 
      tree.write(f) 

    # ---------------------------------------------------------------------- 
    if __name__ == "__main__": 
     feedDoublePosts("./data/original_appt.xml", "appointment") 

 Смежные вопросы

  • Нет связанных вопросов^_^