我正在尝试构建一个脚本来读取XML文件。
这是我第一次分析一个XML,我使用的是带有xml.etree.elementtree的python。我要处理的文件部分如下:
DESCRIPTIONRenese® 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.
ACTIONThe 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)打印相应的段落。
我该怎么做?