python - 在 python 中寻找遍历 ElementTree.findall() 中所有嵌套标签的语法
问题描述
请忍受我,我正在xml
挣扎ElementTree
。python
我已经发布了一个问题:如何使用 Element.findall() 搜索标签并打印其值并提供解决方案工作正常,但后来我意识到这是在标签namespace
上注册的。<parent>
我不知道那条数据会如何改变游戏计划。
<parent xmlns="http://xmlns.test.com/parent" version="1">
有了namespace
,这findall('./*/c/d')
不再是嵌套的tag
(即c/d
)。在这里阅读更多线程,我意识到我必须namespace
像这样添加前缀。
def search(root, wordToSearch):
tags = root.findall('{http://xmlns.test.com/parent}first')
print tags
上面的代码肯定会找到<first>
标签,但是我希望有catch all
类似 ( ) 这样的路径./*/c/d
来遍历<first>
然后<second>
标签。
我担心的是将来xml
可能会有third or even more
标签<parent>
。有没有办法可以在不使用lxml
库的情况下完成它?顺便说一句 - 我有 python2.6.6
和服务器我正在运行脚本2.7.18
。rhel
[更新]
幸运的是,我能够找到解决方案ElementTree 1.3
。
def search(root, wordToSearch):
for child in root: # child represents first and second tag
el = child.tag.split('}', 1)[1] # Remove namespace
el_path = 'xmlns:{0}/xmlns:c/xmlns:d'.format(el)
target_tags = root.findall(el_path, namespaces={'xmlns': 'http://...'})
解决方案
这对你有用吗?
from bs4 import BeautifulSoup
def get_texts(root, tag_name):
return [tag.get_text() for tag in root.find_all(tag_name)]
soup = BeautifulSoup(open('test.xml').read(), features="lxml")
print(get_texts(soup, 'd'))
print(get_texts(soup, 'f'))
输出:
['987', '345']
['xxx', 'yyy', 'zzz', 'ttt', 'hhh', 'www']
推荐阅读
- python - 不会打印项目列表,只打印列表中的第一项
- oracle - HY010 SSIS 中的 Oracle ODBC 函数序列错误?
- azure - ImagePullBackOff 未经授权:需要身份验证
- javascript - 浏览器需要 HTTP 响应,但服务器不允许多个响应
- parsing - 除了叶子,如何创建相同的树?
- c - 如何在C中实现多关键字搜索?
- git - Git 认为我正在推送到不同的(不存在的)存储库?
- java - 如果我的 JVM 是 1.8,为什么我必须将 targetCompatibility 设置为 JavaVersion.VERSION_1_8
- java - c:if 带有来自模型的变量
- java - 如何通过java中的soap头传递多个参数?