Skip to content
This repository has been archived by the owner on Apr 20, 2021. It is now read-only.

Can't get XML elements with default namespace #134

Open
orasik opened this issue Jul 23, 2015 · 0 comments
Open

Can't get XML elements with default namespace #134

orasik opened this issue Jul 23, 2015 · 0 comments

Comments

@orasik
Copy link

orasik commented Jul 23, 2015

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"
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant