XML 迭代根以按标签打印元素
我有一个像这样的 XML 文件:
,我想遍历它以在每次标签为
时打印出温度。
xml.etree.ElementTree 或 lxml 或其他库中是否有内置函数可以用来执行此操作?
这是我当前的努力,但这只是打印所有元素
I have a XML file like this:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理 XML 的最佳方法之一是使用 XPath。 lxml 具有更好的支持 ElementTree 的 XPath 支持有限。但其中任何一个都适用于您的示例。
这是一个使用 lxml 的示例:
如果您确实需要迭代(例如您的 XML 非常大并且有内存问题),您可以使用类似
iter()
或iterparse()
。下面是在 lxml 中使用 iterparse() 的示例:
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:
If you really need to iterate (like if your XML is very large and you have memory issues), you can use something like
iter()
oriterparse()
.Here's an example using iterparse() in lxml:
要迭代直到特定的标签名称,您应该在 root 中循环并使用
.tag
实例来比较它是否等于'temperage'
在这种情况下,对于一个简单的情况我通过使用tag
、attrib
和text
对象显示一些值。输出:
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 usingtag
,attrib
andtext
objects.output: