上周我发布了一个关于需要从xml中提取一些条目的问题。我试图以相当手动的方式进行,并建议使用xml解析器。我一直在尝试使用lxml,但我无法掌握它(我刚开始学习python)。
下面是XML结构的一个例子('ProgramInformation'会有很多分支)
<TVAMain xml:lang="NL" publisher="" publicationTime="2013-09-12T01:43:09+00:00" version="217" xmlns="urn:tva:metadata:2010" xmlns:mpeg7="urn:tva:mpeg7:2008" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:tva:metadata:2010>
<ProgramDescription>
<ProgramInformationTable>
<ProgramInformation programId="crid://bds.tv/95291775">
<BasicDescription>
<Title xml:lang="EN" type="main">Rip Off Britain</Title>
<Synopsis xml:lang="EN" length="short">Consumer series. The team investigates why some viewers have been hit with bills they did not expect for hundreds or even thousands of pounds, and offers some advice.</Synopsis>
<Keyword xml:lang="EN" type="main">bills</Keyword>
<Genre href="urn:tva:metadata:cs:UPCEventGenreCS:2009:82">
<Name xml:lang="EN">Economics</Name>
</Genre>
<Language>EN</Language>
</BasicDescription>
</ProgramInformation>
</ProgramInformationTable>
</ProgramDescription>
</TVAMain>
我可以检索'crid'和'title':
tree = etree.parse('UPC_Medium.xml')
root = tree.getroot()
print (root[0][0][0].attrib)
print (root[0][0][0][0][0].text)
这两个项目将始终位于每个分支下的相同位置(因此理论上我可以以相当粗略的方式检索它们)。我还需要检索该类型,并且可能会移动(因为它之前会有可变数量的'关键字'条目)。
我认为关键是XPATH,但我不明白如何实现它(我在这里看了很多例子)。
有人可以帮助我实现以下目标:
1)实现XPATH以检索并将'crid',title和genre存储到单独的变量中(我将写入外部文件 - 所有这三个都需要一起编写)
2)遍历每个分支以取出上述内容 - 将有数千个条目。
提前致谢!
答案 0 :(得分:1)
请尝试以下操作:
nsmap = {'xmlns': 'urn:tva:metadata:2010'}
for info in root.xpath('//xmlns:ProgramInformation', namespaces=nsmap):
print info.get('programId') # retrieve crid
print info.find('.//xmlns:Title', namespaces=nsmap).text # retrieve title
print info.find('.//xmlns:Genre/xmlns:Name', namespaces=nsmap).text # retrieve genre