2014-09-19 17 views
0

解析EPUB容器我有打算看看提取EPUB 文件中,找到OPF元數據文件的位置,並返回Ruby代碼。所述 路徑OPF文件(相對於EPUB的根目錄)被寫入到 在META-INF/container.xml中發現的XML文件。文件內容是 如下:使用Ruby和LibXNL

<?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和XPath提取根文件路徑

。問題 是的libxml報道,我的XPath表達式是無效的。使用Python和LXML當同一 表達的作品。下面是我的代碼 的相關部分。

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

任何建議將是最受歡迎的。

+0

也許的libxml無法處理這樣一個默認的命名空間?如果你搜索'「// rootfile」'會發生什麼? – 2014-09-19 21:29:10

+0

@Mathias它返回nil。 – 2014-09-19 21:45:15

回答

1

很可能的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'] 

但你需要知道這個命名空間提前硬編碼。查找關於使用命名空間here的更多信息。

+0

這樣做了。順便說一句,全路徑字典鍵是一個字符串,不像我想的那樣是一個符號。我 – 2014-09-20 02:08:49

+0

@HadenPike很高興它的作品。如果它解決了你的問題,請考慮接受這個答案 - 就像你之前提出的問題一樣。謝謝! – 2014-09-20 22:26:05

+0

知道我忘了一些東西。我的錯。 – 2014-09-21 00:23:28