2012-08-07 38 views
5

我有這樣一個XML的工作:(這是EPUB圖書中標準container.xmlPHP的DOMXPath中需要registerNamespace嗎?

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

我想用PHP解析它。這是到目前爲止我的代碼:

$c = new DOMDocument(); 
$c->load($filename); 
$x = new DOMXPath($c); 
//fine up to here! 

//is this even what I'm supposed to be doing? 
$x->registerNamespace('epub', 'urn:oasis:names:tc:opendocument:xmlns:container'); 
$root = $x->query('/epub:container/epub:rootfiles/epub:rootfile'); 

//fine down from here! 
$opf = $root->item(0)->getAttribute('full-path'); //I know I should check if the element's there and if it has the attribute. Not important. 

我的問題是:有沒有辦法不這樣做registerNamespace電話嗎?我不知道如果不同的epubs設置這個值有點不同,我需要這個代碼來處理任何epub我扔它。

回答

2

AFAIK:no。 XML文檔可能會遇到名稱衝突,因此使用名稱空間。您不能在XML文檔上使用XPath,而無需註冊一個或多個名稱空間併爲其設置前綴。

在您的示例中,XML聲明瞭一個默認名稱空間(xmlns="<namespace identifier>"),在這種情況下,沒有一個或多個名稱空間前綴的所有元素都將落入默認名稱空間下。只要你知道,在這個默認的命名空間你要找的是什麼,然後有東西有點簡單:你可以做的反而是沒有硬編碼的默認命名空間和這樣取,

// ... load the DOMDocument ... 

$defaultNamespace = $c->lookupNamespaceURI($c->namespaceURI); 
$x->registerNamespace('epub', $defaultNamespace); 

// ... now query like in your example 
$root = $x->query('/epub:container/epub:rootfiles/epub:rootfile');