Skip to content

Instantly share code, notes, and snippets.

@ekiru
Created August 7, 2010 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekiru/513192 to your computer and use it in GitHub Desktop.
Save ekiru/513192 to your computer and use it in GitHub Desktop.
use v6;
my $xml = '
<test>test</test>
<hat test="20"> hat text here </hat>
<shoe>
<test>asdf</test>
<test>asdf2</test>
<test>asdf3</test>
<test>asdf4</test>
<test>asdf5</test>
<test2>test</test2>
</shoe>
';
sub parse-xml ($xml, %parent = {}) {
my $xml-patt =
/ '<' $<tag>=.+? [<.ws> $<attributes>=.*?]? '>' $<content>=.*?
'</' $<tag> '>' /;
for $xml.match($xml-patt, :global) -> $match {
my $tag = $match<tag>.lc;
my $attributes = ~$match<attributes>;
my $value = ~$match<content>;
if $value ~~ $xml-patt {
%parent{$tag} = parse-xml $value;
} else {
if %parent.exists($tag) {
%parent{$tag} = [ %parent{$tag} ]
unless %parent{$tag} ~~ Array;
%parent{$tag}.push($value);
} else {
%parent{$tag} = $value;
}
}
}
return %parent;
}
say parse-xml($xml).perl;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment