contexts
contexts copied to clipboard
Can't get XML elements with default namespace
Hi,
When there is an element with default namespace that doesn't have a prefix, XMLContext.php can not find it. This is a bug in xpath itself when there is no prefix. Check the first answer:
XPath in SimpleXML for default namespaces
So I have xml similar to the the following:
<?xml version="1.0" encoding="UTF-8"?>
<University>
<ContactInformation>
<Name>University Name</Name>
<Address>University Address</Address>
</ContactInformation>
<body>
<Colleges xmlns="http://ws.someuni.com/ver1">
<Entries countEntries="4">
<college name="college1"/>
<college name="college2"/>
<college name="college3"/>
<college name="college4"/>
</Entries>
</Colleges>
</body>
</University>
If I try to get countEntries attribute or Entries element using behatch context, it will not return anything.
I have tried to use rootns as default namespace but that didn't work either.
I made a fix to this issue by adding namespace(s) with counters inside getNamesapces method.
// file = Sanpi\Behatch\Context\XmlContext
private function getNamespaces(\DOMDocument $dom = null)
{
$xml = $this->getSimpleXml($dom);
$namespaces = $xml->getNamespaces(true);
// fix
$counter = 0;
foreach($namespaces as $key => $value ){
if(empty($key)) {
$counter++;
$correctedNamespaces['ns'.$counter] = $value;
} else {
$correctedNamespaces[$key] = $value;
}
}
return $correctedNamespaces;
}
Then to get countEntries you can use the following phrase:
Then the XML attribute "countEntries" on element "//University/body/ns1:Colleges/ns1:Entries" should be equal to "4"