繁体   English   中英

在具有名称空间的xml文件中使用lxml库的Xpath问题

[英]Xpath issue using lxml library in an xml file with namespaces

我正在尝试使用名称空间从xml文件中选择一个xml节点。 我已经有一个选择工作了,但不能让第二个选择工作。

这是简化的xml(在python代码中存储为BookMetaData):

<?xml version='1.0' encoding='utf-8'?>
<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="calibre_id">
  <metadata xmlns:opf="http://www.idpf.org/2007/opf" 
  xmlns:dc="http://purl.org/dc/elements/1.1/" 
  xmlns:calibre="http://calibre.kovidgoyal.net/2009/metadata">
    <dc:title>De blanke masai V2</dc:title>
    <meta name="calibre:user_metadata:#origfieldvalue" content="{&quot;is_category&quot;: true, &quot;#extra#&quot;: null}"/>
  </metadata>
</package>

这是我到目前为止编写的python代码:

#!/usr/bin/python
# All imports
import lxml.html
import lxml.etree

# namespaces
theNamespaces = {'opf' : "http://www.idpf.org/2007/opf", 
'dc' : "http://purl.org/dc/elements/1.1/", 
'calibre' : "http://calibre.kovidgoyal.net/2009/metadata",
'unique-identifier' : "calibre_id" }

# This part is working perfectly
theXMLdoc = lxml.etree.fromstring(BookMetaData)
theElement2 = theXMLdoc.xpath("//dc:title", namespaces = theNamespaces)[0]
print "lxml.html Source Value:"
print( theElement2.text)
print ""


# This part only returns an emtpy list
theOrigValueElement = theXMLdoc.xpath("//meta[@name='calibre:user_metadata:#origfieldvalue']", namespaces = theNamespaces)
print "Original value of OrigFieldValue:"
print( theOrigValueElement)
print ""

我尝试过的不起作用的事情:
如何使用xpath-from-lxml-on-null-namespaced-nodes命名空间http://www.idpf.org/2007/opf ”两次使用,一次在“包”中,没有前缀,一次在“元数据”中带有前缀。 因此,向名称空间添加另一个前缀将无济于事。

有人可以帮我弄这个吗?

如果您只是将opf前缀添加到xpath语句中

//opf:meta[@name='calibre:user_metadata:#origfieldvalue']

这似乎可以解决问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM