【发布时间】:2018-07-17 14:42:12
【问题描述】:
我正在解析 XML 文件,我有一个来自 here 的后续问题。从下面的 XML 字段:
<enrollment type="Anticipated">30</enrollment>
我想把预期的单词和数字拉出来。 在我拥有的文件中,“注册类型”/“注册”在文件之间将保持稳定,但“预期”不会(例如,有时它会显示“实际”或其他内容)并且数量也不会保持稳定。
我试过的代码:
from lxml import etree
import sys
import glob
list_to_get = ['enrollment']
list_of_files = glob.glob('*xml')
for each_file in list_of_files:
# try:
tree = etree.parse(each_file)
root = tree.getroot()
for node in root.xpath("//" + 'enrollment'):
for e in node.xpath('descendant-or-self::*[not(*)]'):
if e.attrib:
print e.attrib
print e.find('type')
print e.find('.//type')
print e.attrib['type']
print e.find(e.attrib['type']).text
使用这种方法,我可以提取类型(例如预期/实际),但我找不到任何方法提取数字。如果有人知道我应该使用的打印线,我将不胜感激。
我确实看过一些类似的问题(例如here),但他们的建议似乎对我不起作用。
【问题讨论】:
-
你能看看这里吗:
https://docs.python.org/2/library/xml.etree.elementtree.html#finding-interesting-elements -
非常感谢,现在才开始进行 xml 解析,非常感谢所有帮助。我确实看过这个,但是不够仔细/我不明白。谢谢。