XML计数和打印元素


<?xml version="1.0" encoding="utf-8"?>
<export_full date="2022-03-15 07:01:30" version="20160107">
<items>
<item code="A1005" image="https://www.astramodel.cz/images/A/800x600/A1005.jpg" imageDate="2014-04-08" name="Uhlíková tyčka 0.6mm (1m)" brandId="32" brand="ASTRA" czk="89.00" eur="3.50" czksmap="89.00" eursmap="3.50" hasPrice="true" created="2014-01-09" changed="" new="false" stock="true" date="" stock2="true" date2="" stock3="high" date3="" discontinued="false" weight="0.001" length="0.001" width="0.001" height="1.000" recycling_fee="">
<descriptions>
<description title="Charakteristika" order="1">&lt;p&gt;Tyč z uhlíkových vláken kruhového průřezu ø0.6&amp;nbsp;mm v délce 1&amp;nbsp;m. Hmotnost 0,3&amp;nbsp;g&lt;/p&gt;</description>
</descriptions>
</item>

我有一个XML文件,它非常大,但我正在尝试计算项目的总数,并尝试键入每个项目的名称属性,在上面您可以看到每个带有标记的项目的外观。当我试图打印总项目数时,我确实得到了一个数字,但我不确定我是否以正确的方式进行,而且就名称属性而言,到目前为止我一无所获,请帮忙。

import xml.etree.ElementTree as ET
tree = ET.parse('export_full.xml')
root = tree.getroot()
test = [elem.tag for elem in root.iter("item")]
print(len(test))
for item in root.iter('./item[@name]'):
print(item.attrib)

要计算XPath表达式,请使用findall((函数。注意";项目";元素是";项目";元素,因此如果使用绝对路径,则需要将"items"添加到XPath,否则使用"//项目[@name]";。

for item in root.findall('./items/item[@name]'):
print(item.attrib)

如果您希望它遍历所有项,并将name属性添加到列表中。

items = [elem.get('name') for elem in root.iter("item")]
print(len(items), items)  # print count of items and list of names

如果XML是巨大的,那么您可以通过使用iterparse((函数对XML进行增量解析来获益。

下面的示例遍历XML,如果标记为"item",则打印其"name"属性。您可以添加任何要检查的逻辑。

count = 0
for _, elem in ET.iterparse('export_full.xml'):
if elem.tag == 'item':
print(elem.get('name')) # print out just the name
count += 1
# print(elem.attrib) # print out all attributes
print(count) # display number of items

最新更新