繁体   English   中英

在PHP的DOMXPath中是否需要registerNamespace?

[英]Is registerNamespace necessary in PHP's DOMXPath?

我正在使用这样的XML :(它是epub书中的标准container.xml

<?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调用? 我不确定不同的epub是否设置了这个值有点不同,我需要这个代码来处理我抛出的任何epub。

AFAIK:没有。 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');

要详细说明Max的响应,如果您的XML文档本身没有声明默认命名空间,那么从技术上讲,您可以在DOMXPath上注册命名空间。 这意味着文档中的所有元素都不会与任何名称空间相关联。 但是,由于您正在使用看似行业标准的内容,我的猜测是声明XML文档本身的名称空间是必要的。 如果您的XML文档如下所示,那么您可以跳过registerNamespace声明,而不必在查询中使用'epub'的命名空间前缀。

 <?xml version="1.0"?> <container version="1.0"> <rootfiles> <rootfile full-path="OEBPS/9780765348210.opf" media-type="application/oebps-package+xml"/> </rootfiles> </container> 

但是,大多数不在单个组织中使用的XML文档都会声明一个默认的命名空间。

暂无
暂无

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

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