的Python解析XML/OPF文件

问题描述:

我想读的Python解析XML/OPF文件

<dc:title> </dc:title> 

之间的条目这是XML:

<?xml version='1.0' encoding='utf-8'?> 
<package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="calibre-uuid"> 
<metadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:opf="http://www.idpf.org/2007/opf" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:calibre="http://calibre.kovidgoyal.net/2009/metadata" xmlns:dc="http://purl.org/dc/elements/1.1/"> 
<meta name="calibre:series_index" content="1"/> 
<dc:language>UND</dc:language> 
<dc:creator opf:file-as="Unbekannt" opf:role="aut">Johann Wolfgang von Goethe</dc:creator> 
<meta name="calibre:timestamp" content="2009-10-08T07:26:21"/> 
<dc:title>Faust_I_</dc:title> 
<meta name="cover" content="cover"/> 
<dc:date>2009-10-08T07:26:21</dc:date> 
<dc:contributor opf:role="bkp">calibre (0.6.13) [http://calibre-ebook.com]</dc:contributor> 
<dc:identifier id="calibre-uuid">urn:uuid:3cd4b26f-39a3-4783-9730-a86c26b30818</dc:identifier> 

这是我的代码:

from xml.etree import ElementTree as ET 
tree = ET.parse('content.opf') 
root = tree.getroot() 
dc_namespace = "http://purl.org/dc/elements/1.1/" 
print (root.attrib[ET.QName(dc_namespace, 'title')]) 

输出错误:

Traceback (most recent call last): 
File "C:\Users\User\Documents\Visual Studio 2017\Projects\PythonApplication1\Modul1.py", line 8, in <module> 
print (root.attrib[ET.QName(dc_namespace, 'title')]) 
KeyError: <QName '{xmlns:dc}title'> 

怎么了?

+0

什么是您当前的埃罗R /输出? – MattR

+0

增加了输出错误。 – aquisic

+0

XML中缺少一对结束标记。 – mzjn

你可以使用:

root[number][number] 

访问的元素。 例如在

<base> 
    <element1> 
     <element2>asdada</element2> 
    </element> 
</base> 

根[0] [0]将给ü元件2

+0

是的,我以前使用过,但它不是每次都是相同的元素编号,但每次都是相同的标签() – aquisic

+0

您可以使用minidom。 – krishnair1123

什么你正在寻找(<dc:title>)是一个元素,而不是一个属性。这里是你如何能得到它的值:

from xml.etree import ElementTree as ET 

tree = ET.parse('content.opf') 
title = tree.find(".//{http://purl.org/dc/elements/1.1/}title") 
print(title.text) 

输出:

Faust_I_ 

相关参考文献: