python xml etree amp,用python etree打印XML的嵌套元素

本文介绍了作者初次使用Python的xml.etree.ElementTree模块解析XML文件的经历。示例代码展示了如何读取XML文件并打印标题,同时作者试图打印与标题相关的段落内容。目前代码能正确打印标题,但在遍历段落时遇到问题,导致无法按预期输出。作者寻求解决方案以正确识别标题并打印对应的段落文本。
摘要由CSDN通过智能技术生成

我正在尝试构建一个脚本来读取XML文件。

这是我第一次分析一个XML,我使用的是带有xml.etree.elementtree的python。我要处理的文件部分如下:

DESCRIPTION

Renese® is designated generically as polythiazide, and chemically as 2H-1,2,4-Benzothiadiazine-7-sulfonamide, 6-chloro-3,4-dihydro-2-methyl-3-[[(2,2,2-trifluoroethyl)thio]methyl]-, 1,1-dioxide. It is a white crystalline substance, insoluble in water but readily soluble in alkaline solution.

Inert Ingredients: dibasic calcium phosphate; lactose; magnesium stearate; polyethylene glycol; sodium lauryl sulfate; starch; vanillin. The 2 mg tablets also contain: Yellow 6; Yellow 10.

ACTION

The mechanism of action results in an interference with the renal tubular mechanism of electrolyte reabsorption. At maximal therapeutic dosage all thiazides are approximately equal in their diuretic potency. The mechanism whereby thiazides function in the control of hypertension is unknown.

完整文件可从以下位置下载:

这里是我的代码:

import xml.etree.ElementTree as ElementTree

import re

with open("ABD6ECF0-DC8E-41DE-89F2-1E36ED9D6535.xml") as f:

xmlstring = f.read()

# Remove the default namespace definition (xmlns="http://some/namespace")

xmlstring = re.sub(r'\sxmlns="[^"]+"', '', xmlstring, count=1)

tree = ElementTree.fromstring(xmlstring)

for title in tree.iter('title'):

print(title.text)

到目前为止,我可以打印标题,但我还想打印标签中捕获的相应文本。

我尝试过:

for title in tree.iter('title'):

print(title.text)

for paragraph in title.iter('paragraph'):

print(paragraph.text)

但是我没有从段落中输出。

for title in tree.iter('title'):

print(title.text)

for paragraph in tree.iter('paragraph'):

print(paragraph.text)

我打印段落的文本,但(显然)它是为XML结构中的每个标题一起打印的。

我想找到一种方法1)识别标题;2)打印相应的段落。

我该怎么做?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值