Created
August 7, 2010 20:53
-
-
Save ekiru/513192 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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