XML 迭代根以按标签打印元素

发布于 2025-01-09 22:00:07 字数 460 浏览 2 评论 0原文

我有一个像这样的 XML 文件:

在此处输入图像描述

,我想遍历它以在每次标签为 时打印出温度。

xml.etree.ElementTree 或 lxml 或其他库中是否有内置函数可以用来执行此操作?

这是我当前的努力,但这只是打印所有元素

在此处输入图像描述

I have a XML file like this:

enter image description here

and I want to iterate through it to print out the temperature every time the tag is <temperature>.

Is there any functions built into xml.etree.ElementTree or lxml or other libraries I can use to do this?

Here's my current effort but that just prints all of the elements

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

乖乖兔^ω^ 2025-01-16 22:00:07

处理 XML 的最佳方法之一是使用 XPath。 lxml 具有更好的支持 ElementTree 的 XPath 支持有限。但其中任何一个都适用于您的示例。

这是一个使用 lxml 的示例:

from lxml import etree

tree = etree.parse("dub_airport.xml")

for temp in tree.xpath(".//temperature"):
    print(f"The temperature value is \"{temp.text}\".")

如果您确实需要迭代(例如您的 XML 非常大并且有内存问题),您可以使用类似 iter()iterparse()

下面是在 lxml 中使用 iterparse() 的示例:

from lxml import etree

for event, elem in etree.iterparse("dub_airport.xml", tag="temperature", events=("start",)):
    print(f"The temperature value is \"{elem.text}\".")
    elem.clear()

One of the best ways to process XML is with XPath. lxml has better support as ElementTree's XPath support is limited. But either one would work in your example.

Here's an example using lxml:

from lxml import etree

tree = etree.parse("dub_airport.xml")

for temp in tree.xpath(".//temperature"):
    print(f"The temperature value is \"{temp.text}\".")

If you really need to iterate (like if your XML is very large and you have memory issues), you can use something like iter() or iterparse().

Here's an example using iterparse() in lxml:

from lxml import etree

for event, elem in etree.iterparse("dub_airport.xml", tag="temperature", events=("start",)):
    print(f"The temperature value is \"{elem.text}\".")
    elem.clear()
箜明 2025-01-16 22:00:07

要迭代直到特定的标签名称,您应该在 root 中循环并使用 .tag 实例来比较它是否等于 'temperage' 在这种情况下,对于一个简单的情况我通过使用 tagattribtext 对象显示一些值。

>>> for child in root:
...     for child_tag in child:
...         if (child_tag.tag == 'temperature'):
...             print(child_tag.tag, child_tag.attrib, child_tag.text)
...

输出:

temperature {} 11
temperature {} 11
temperature {} 11

To iterate until a specific tag name you should loop in root and use .tag instance to compare if it is equal to 'temperature' in this case, for a simple case I have display some values by using tag, attrib and text objects.

>>> for child in root:
...     for child_tag in child:
...         if (child_tag.tag == 'temperature'):
...             print(child_tag.tag, child_tag.attrib, child_tag.text)
...

output:

temperature {} 11
temperature {} 11
temperature {} 11
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文