You need to enable JavaScript to run this app. Perl中使用XML::LibXML提取指定group下嵌套cell节点并生成哈希的方法
优惠活动
大模型
产品
解决方案
定价
更多

Perl中使用XML::LibXML提取指定group下嵌套cell节点并生成哈希的方法

XML::LibXML 批量获取所有层级cell节点的实现方案

内置API方案(推荐,无需手动递归)

XML::LibXML 原生支持 XPath 查询语法,可一次性获取指定节点下任意嵌套层级的子孙节点,不需要逐层调用getChildrenByTagName。

核心实现逻辑

  1. 先用XPath定位name属性为stdcell_globalsubtypes的group节点
  2. 在该group节点的上下文下,用*.//cell*表达式直接匹配所有层级的cell子孙节点
  3. XPath返回的节点列表自动按照文档顺序排列,和XML中的嵌套顺序完全一致

示例代码

use XML::LibXML;

# 加载XML内容(替换为你实际的XML字符串/文件路径)
my $xml_content = <<'XML';
<libraries>
 <group name="stdcell_globalsubtypes">
   <cell type="a" optional="1">
    <cell type="b" optional="1">
      <cell type="c" optional="1" >
        <cell type="d" optional="1" >
         <cell type="e" optional="1"/>
       </cell>
     </cell>
   </cell>
 </cell>
</group>
</libraries>
XML

my $dom = XML::LibXML->load_xml(string => $xml_content);

# 定位目标group节点
my $target_group = $dom->findnodes('//group[@name="stdcell_globalsubtypes"]')->shift();
die "未找到指定group节点" unless $target_group;

# 一次性获取该group下所有层级的cell节点,自动按文档顺序返回
my @cell_nodes = $target_group->findnodes('.//cell');

# 生成需求格式的哈希
my %result_hash;
my $seq = 1;
foreach my $cell (@cell_nodes) {
    $result_hash{$seq++} = $cell->getAttribute('type');
}

# 最终%result_hash的内容为 (1=>'a', 2=>'b', 3=>'c', 4=>'d', 5=>'e')

备选:手动递归遍历实现

如果无法使用XPath,可通过递归遍历所有子节点实现相同效果:

递归逻辑

  • 从目标group节点开始,逐层级遍历所有直接子元素
  • 遍历过程中识别标签名为cell的节点,加入结果列表
  • 对每个子元素(无论是否为cell节点)继续递归遍历其内部嵌套的子节点,确保所有层级的cell都能被采集到

示例代码

# 递归采集cell节点的函数
sub collect_cells_recursive {
    my ($parent, $cell_list) = @_;
    # 仅处理元素节点,跳过文本、注释等非节点类型
    foreach my $child ($parent->childNodes()) {
        next unless $child->nodeType == XML_ELEMENT_NODE;
        # 匹配到cell节点则加入结果
        push @$cell_list, $child if $child->nodeName eq 'cell';
        # 递归遍历当前子节点的内部结构
        collect_cells_recursive($child, $cell_list);
    }
}

# 调用方式
my @cell_nodes;
collect_cells_recursive($target_group, \@cell_nodes);
# 后续生成哈希的逻辑和XPath方案完全一致

注意事项

  • 两种方案返回的节点顺序均为文档原生顺序,无需额外排序
  • 递归实现时必须过滤非元素节点,否则会因文本节点不支持nodeName方法抛出异常
  • XPath方案的匹配逻辑更严谨,可自动处理节点名大小写、属性精确匹配等场景

内容的提问来源于stack exchange,提问作者Dhanashri P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 10:36:03