在python中从标签名称中查找xml文本内容 [英] Finding xml text content from tag name in python

查看:38
本文介绍了在python中从标签名称中查找xml文本内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定以前有人问过这种类型的问题,但我似乎无法找到正确的词组来自己找到答案...

I certain this type of question has been asked before, but I can't seem to get the right set of words to find the answer myself...

我有一个 XML 文件,例如

I've got an XML file, for example

<document>
   <page>
      <title>title1</title>
      <id>1</id>
      <text>this is text1</text>
   </page>
   <page>
      <title>title2</title>
      <id>2</id>
      <text>this is text2</text>
   </page>
   <page>
      <title>title3</title>
      <id>3</id>
      <comment>random comment</comment>
      <text>this is text3</text>
   </page>
</document>

我试图找到一种方法,理想情况下,将标签中的每个值存储到一个数组中.

I am trying to find a way to, ideally, store each values within tags into an array.

现在我最初尝试只用下面的代码打印所有内容,但这只工作到有随机标签抛出索引的时候.那么,有没有办法简单地从标签中获取文本?还是绝对需要知道数组索引?

Now I had originally tried just printing everything with the code below, but that only worked until the time where there is the random tag which throws off the indexing. So, is there a way to simple get the text from tag? Or is there an absolute need to know the array index?

import xml.etree.ElementTree as ET
tree = ET.parse('./xml_file.xml')
root = tree.getroot()

for child in root:
    print(child[2].text)

如果这是一个常见问题,我很抱歉,我真的无法在网上找到任何答案.

I apologies if this is common question, I really couldn't figure out any answers online.

推荐答案

由于您的问题听起来像是您正在寻找特定的密钥,您可以简单地使用 find().text 获取具有该名称的 XML 键的内容

Since from your question it sounds like you're looking to get a specific key, you can simple use find(<key_name>).text to get the contents of the XML key with that name

import xml.etree.ElementTree as ET
tree = ET.parse('./all_foods.xml')
root = tree.getroot()
for x in root:
    print x.find("title").text

>>>
   title1
   title2
   title3

这篇关于在python中从标签名称中查找xml文本内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆