使用Ruby和LibXNL解析EPUB容器

使用Ruby和LibXNL解析EPUB容器,ruby,xml,xpath,epub,Ruby,Xml,Xpath,Epub,我有一个Ruby代码,用于查看提取的EPUB内部 文件,找到OPF元数据文件的位置并返回它。这个 写入OPF文件的路径(相对于EPUB的根目录) 指向META-INF/container.XML中的XML文件。文件内容是 详情如下: <?xml version="1.0"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles&

我有一个Ruby代码,用于查看提取的EPUB内部 文件,找到OPF元数据文件的位置并返回它。这个 写入OPF文件的路径(相对于EPUB的根目录) 指向META-INF/container.XML中的XML文件。文件内容是 详情如下:

<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
   <rootfiles>
      <rootfile full-path="content.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>

任何建议都是非常受欢迎的。

LibXML处理默认名称空间的方式可能与lxml不同。尝试为命名空间定义别名(即前缀)

require 'libxml'
include LibXML
container = File.join("META-INF", "container.xml")
tree = XML::Document.file(container)
tree.root.namespaces.default_prefix = 'opf'
rootfile = tree.find_first("//opf:rootfile")['full-path']
或者,将
find_first
与包含命名空间声明的第二个参数一起使用:

require 'libxml'
include LibXML
container = File.join("META-INF", "container.xml")
tree = XML::Document.file(container)
rootfile = tree.find_first("//opf:rootfile", "opf:urn:oasis:names:tc:opendocument:xmlns:container)['full-path']

但是,您需要提前了解这个名称空间并对其进行硬编码。查找有关使用名称空间的详细信息。

也许LibXML无法以这种方式处理默认名称空间?如果搜索
“//rootfile”
,会发生什么?@Mathias它返回nil。就是这样。另外,完整路径字典键是一个字符串,而不是我所认为的符号。I@HadenPike很高兴它起作用了。请考虑接受这个答案,如果它解决了你的问题——就像你以前的问题一样。谢谢我知道我忘了什么。我的错。
require 'libxml'
include LibXML
container = File.join("META-INF", "container.xml")
tree = XML::Document.file(container)
rootfile = tree.find_first("//opf:rootfile", "opf:urn:oasis:names:tc:opendocument:xmlns:container)['full-path']