我有一个数组引用,其中包含一些数组引用.嵌套数组引用还包含数组引用.(这是XML :: Parser的树样式.)
my $Filename = "sample.xml";
my $Parser = new XML::Parser( Style => 'tree' );
my $Tree = $Parser->parsefile( $Filename );
Run Code Online (Sandbox Code Playgroud)
这里$Tree是数组引用它将是数组引用,内容和嵌套深度都取决于xml文件.我想遍历嵌套数组$Tree并打印内容.
这是一个简单的版本:
use strict;
use warnings;
sub printElement
{
my ($tag, $content) = @_;
if (ref $content) {
# This is a XML element:
my $attrHash = $content->[0];
print "<$tag>"; # I'm ignoring attributes
for (my $i = 1; $i < $#$content; $i += 2) {
printElement(@$content[$i, $i+1]);
}
print "</$tag>";
} else {
# This is a text pseudo-element:
print $content; # I'm not encoding entities
}
} # end printElement
sub printTree
{
# The root tree is always a 2-element array
# of the root element and its content:
printElement(@{ shift @_ });
print "\n";
}
# Example parse tree from XML::Parser:
my $tree =
['foo', [{}, 'head', [{id => "a"}, 0, "Hello ", 'em', [{}, 0, "there"]],
'bar', [ {}, 0, "Howdy", 'ref', [{}]],
0, "do"
]
];
printTree($tree);
Run Code Online (Sandbox Code Playgroud)
这不会打印属性,但您可以通过它们访问它们$attrHash.它也不对文本中的实体进行编码,因此生成的输出可能不会是格式良好的XML.我将这些作为练习留给读者.:-)
| 归档时间: |
|
| 查看次数: |
4886 次 |
| 最近记录: |