我正在使用 CPANXML::LibXML
模块来处理下面的 XML 数据。我需要确定每个元素是否有子元素。环顾四周,我找不到任何用于此目的的示例。
<A>
<ts>2012</ts>
<T>M1</T>
<T>M2</T>
<B>
<id>PC</id>
<r>10</r>
<r>30</r>
</B>
</A>
这是我写的 Perl 代码
#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my ($x,$elname,$haschild)= ();
my $parser = XML::LibXML->new();
my $npo = $parser->parse_file("test.xml");
my $rootel = $npo -> getDocumentElement();
$elname = $rootel -> nodeName();
print "Root name=$elname\n";
foreach $x ($rootel->childNodes) {
$elname = $x -> nodeName();
$haschild = $x->hasChildNodes;
print "Child name = $elname and has child = $haschild.\n" unless ($elname =~ /#text/i);
}
虽然我曾经childNodes
遍历每个节点,但我找不到一种简单的方法来确定该节点是否有子节点。
我希望在遍历所有节点后得到结果:
A: Has children
ts: Has none
T: has none
T: has none
B: Has children
id: Has none
r: Has none
r: Has none
我得到的结果是这样的:
Root name=A
Child name = ts and has child = 1.
Child name = T and has child = 1.
Child name = T and has child = 1.
Child name = B and has child = 1.
hasChildNodes
条件检查后似乎所有节点都返回 true 。