gpt4 book ai didi

python - 在 XML 文件中查找标签

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:26 25 4
gpt4 key购买 nike

我有如下 xml 文件:

<article>
<MainText>
<Big> HDhsdjdsd </Big>
<Small> jdhdhksdj </Small>
<Big><text> jsdhjsadh </text> <footnote> 1 </footnote> <text> hsdhsdh </text> </Big>
</MainText>
</article>

我的问题是:由于“脚注”并非每次都位于同一位置(即在文本标签之后;但总是在“MainText”中),所以我不知道一般如何获取此标签。谁能告诉我这怎么可能?我用“findall”尝试过,但这不起作用。谢谢你的帮助! :)

最佳答案

使用.//MainText//footnote xpath表达式。它将在 MainText 内的任何位置找到 footnote 标记:

import xml.etree.ElementTree as ET

data = """<article>
<MainText>
<Big> HDhsdjdsd </Big>
<Small> jdhdhksdj </Small>
<Big><text> jsdhjsadh </text> <footnote> 1 </footnote> <text> hsdhsdh </text> </Big>
</MainText>
</article>"""

tree = ET.fromstring(data)

print tree.find('.//MainText//footnote').text.strip()

打印1

希望有帮助。

关于python - 在 XML 文件中查找标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com