0
上週我發佈了一個關於需要從xml中提取一些條目的問題。我試圖用相當手動的方式來完成,並且建議使用xml解析器。我一直在試驗lxml,但我無法得到它的竅門(我剛剛開始學習python)。需要幫助瞭解特定XML示例中的XPATH
的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' 和 '標題':
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」,標題和流派到單獨的變量(我會寫信給一個外部文件 - 所有這三個必須寫在一起)
2)迭代通過每個分支拉出上述 - 將有成千上萬的條目。
在此先感謝!
感謝您的反饋意見。這很有用。所以我的理解是,在第一行(nsmap)中,我在樹的頂部選擇一個唯一值併爲其命名(xmlns)。第二行設置我工作的地方的「根」,後面的行相對於該根工作。因此,我假定我想要拉出的任何其他標籤都被指定爲.//xmlns:tag_name/xmlns:next_level_tag_name。那是對的嗎? – Nick
@Nick,請參閱['lxml.etree教程 - 名稱空間]](http://lxml.de/tutorial.html#namespaces)。 – falsetru