如何用命名空间解析 XML 文件? [英] How parsing out XML file with namespaces?
问题描述
我知道之前有人发布过类似的问题,但我无法解析出带有命名空间的 XML 文件.
I know similar questions were posted before, but I can't parse out this XML file with namespaces.
这是它的链接,因为它太大了,不能在这里发布:https://tsdrapi.uspto.gov/ts/cd/casestatus/sn86553893/info.xml
Here is the link to it because it's too big to post here: https://tsdrapi.uspto.gov/ts/cd/casestatus/sn86553893/info.xml
我尝试使用 simplexml_load_file
但这不会创建 xml 对象.然后我发现了类似的问题并尝试了类似的方法,前提是我已经下载了名为 86553893.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
这是我的php代码:
$xml= new SimpleXMLElement("86553893.xml");
foreach($xml->xpath('//com:ApplicationNumber') as $event) {
var_export($event->xpath('com:ApplicationNumberText'));
}
推荐答案
您必须在要使用的每个元素上注册命名空间:
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'));
}
这在 DOM 中有所不同,您使用 DOMXPath 实例,因此它只是一个对象,您只需注册一次命名空间.
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));
}
这篇关于如何用命名空间解析 XML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!