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"><p>Tyč z uhlíkových vláken kruhového průřezu ø0.6&nbsp;mm v délce 1&nbsp;m. Hmotnost 0,3&nbsp;g</p></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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
评估Xpath表达式使用函数。请注意,“项目”元素是“项目”元素的孩子,因此,如果使用绝对路径,则需要将'项目'添加到XPath中,否则使用“ .//item [@name]”。
如果您希望它迭代所有项目,并将名称属性添加到列表中。
如果XML很大,那么您可以使用 iterparse()函数。
下面的示例迭代XML,如果标签为“项目”,则打印其“名称”属性。您可以添加要检查的任何逻辑。
To evaluate an XPath expression use findall() function. Note the "item" elements are children of "items" element so need to add 'items' to the XPath if using an absolute path otherwise use ".//item[@name]".
If you want it iterate over all items and add the name attribute to a list.
If XML is huge then you can benefit by doing an incremental parse of the XML using iterparse() function.
Example below iterate overs the XML and if tag is 'item' then print its 'name' attribute. You can add whatever logic you want to check.