diff --git a/lib/IdPAccountManager/SAMLMetadata.pm b/lib/IdPAccountManager/SAMLMetadata.pm
index 996d5715421b24f319dd5417f5ce66c828481076..b678ef6d59fa861ca74eadc86a1a35a5582b4dd2 100644
--- a/lib/IdPAccountManager/SAMLMetadata.pm
+++ b/lib/IdPAccountManager/SAMLMetadata.pm
@@ -38,12 +38,12 @@ sub parse {
     my ($self, %args) = @_;
 
     my @array;
-    foreach my $EntityDescriptor (
+    ENTITY: foreach my $EntityDescriptor (
         @{ $self->{doc}->getElementsByLocalName('EntityDescriptor') })
     {
 
         my $id = $EntityDescriptor->getAttribute('entityID');
-        next if $args{entity_id} && $args{entity_id} ne $id;
+        next ENTITY if $args{entity_id} && $args{entity_id} ne $id;
 
         my $data = {
             entityid => $id
@@ -55,6 +55,8 @@ sub parse {
             next unless $child->nodeType() == XML_ELEMENT_NODE;
 
             if ($child->localname() eq 'IDPSSODescriptor') {
+                next ENTITY
+                    if $args{entity_type} && $args{entity_type} ne 'idp';
 
                 $data->{type} = 'idp';
 
@@ -80,6 +82,8 @@ sub parse {
                 }
 
             } elsif ($child->localname() eq 'SPSSODescriptor') {
+                next ENTITY
+                    if $args{entity_type} && $args{entity_type} ne 'sp';
 
                 $data->{type} = 'sp';
 
@@ -165,9 +169,6 @@ sub parse {
             }
         }
 
-        ## Filter entities based  on type
-        next if $args{entity_type} && $args{entity_type} ne $data->{type};
-
         ## Merge domains in a single string
         my $domains = join(',', @{ $data->{domain} })
           if ($data->{domain});