Alexander Monzon
Alexander Monzon

Reputation: 3

Parse XML file with Simple XML and xpath

I'm trying to obtain the values of the nodes "/entry/comment[type="subcellular location"]/subcellularLocation/location" from this file http://www.uniprot.org/uniprot/P12345.xml

I'm using SimpleXML and xpath but I can't access to this nodes with:

$var = "http://www.uniprot.org/uniprot/P12345.xml";
$Unip_result= new SimpleXMLElement($var, NULL, TRUE);

$value=$Unip_result->xpath("/entry/comment[@type='subcellular location']");

The result is an empty array...

Upvotes: 0

Views: 97

Answers (2)

har07
har07

Reputation: 89285

Your XML has default namespace (the one without prefix : xmlns="...."). The element where the default namespace declared and all of it's descendant without prefix and without different default namespace are considered in the ancestor's default namespace. So, you need to register a prefix that point to default namespace URI and use that prefix in the XPath :

$var = "http://www.uniprot.org/uniprot/P12345.xml";
$Unip_result = new SimpleXMLElement($var, NULL, TRUE);
$Unip_result->registerXPathNamespace('ns', 'http://uniprot.org/uniprot');

$value = $Unip_result->xpath("/ns:uniprot/ns:entry/ns:comment[@type='subcellular location']");

Upvotes: 1

ThW
ThW

Reputation: 19492

The XML has namespaces, you need to register a prefix for it and use the prefix in the XPath expression. Check SimpleXMLElement::registerXpathNamespace().

Upvotes: 1

Related Questions