2012-08-07 54 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');