How parsing out XML file with namespaces?

梦想的初衷 提交于 2019-12-12 04:38:34

问题


I know similar questions were posted before, but I can't parse out this XML file with namespaces.

Here is the link to it because it's too big to post here: https://tsdrapi.uspto.gov/ts/cd/casestatus/sn86553893/info.xml

I tried using simplexml_load_file but that does not create xml object. Then I found similar problems and try something like this, provided I already downloaded file named it 86553893.xml

Here is my php code:

$xml= new SimpleXMLElement("86553893.xml");
                            foreach($xml->xpath('//com:ApplicationNumber') as $event) {
                                var_export($event->xpath('com:ApplicationNumberText'));
                        }

回答1:


You will have to register the namespaces on each element you want to use them:

$xml= new SimpleXMLElement("86553893.xml");
$xml->registerXpathNamespace('com', 'http://www.wipo.int/standards/XMLSchema/Common/1');
foreach ($xml->xpath('//com:ApplicationNumber') as $event) {
  $event->registerXpathNamespace(
    'com', 'http://www.wipo.int/standards/XMLSchema/Common/1'
  );                         
  var_export($event->xpath('com:ApplicationNumberText'));
}

This is different in DOM, you use an DOMXPath instance, so it is only a single object and you will have to register the namespaces only once.

$dom = new DOMDocument();
$dom->load("86553893.xml");
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('com', 'http://www.wipo.int/standards/XMLSchema/Common/1');

foreach ($xpath->evaluate('//com:ApplicationNumber') as $event) {
  var_export($xpath->evaluate('string(com:ApplicationNumberText)', $event));
}



回答2:


You need pass the 3th param as true:

<?php

$xml= new SimpleXMLElement("info.xml", NULL, true);
                            foreach($xml->xpath('//com:ApplicationNumber') as $event) {
                                    var_export($event->xpath('com:ApplicationNumberText'));

}

Output:

array (
  0 => 
  SimpleXMLElement::__set_state(array(
  )),
)

you can read more about SimpleXMLElement in:

http://php.net/manual/en/simplexmlelement.construct.php



来源:https://stackoverflow.com/questions/29546831/how-parsing-out-xml-file-with-namespaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!