【问题标题】:How to get the hierarchy structure of an element using XML::LibXML in perl如何在 perl 中使用 XML::LibXML 获取元素的层次结构
【发布时间】:2020-03-16 06:17:47
【问题描述】:

就像在这个 HTML sn-p 中一样: <div class="c1"><span class="c2"><b class="c3"/></span></div> b 元素的预期层次结构应该是:div.c1 span.c2 b.c3

【问题讨论】:

    标签: perl xml-libxml


    【解决方案1】:

    XML::LibXML::Node 中有 parentNode 方法,它只是返回父节点。这样您就可以找到您感兴趣的节点 (b) 然后向上“钻取”到树的顶部,收集有关节点的合适信息。对于所需的 element.class 格式:

    use warnings;
    use strict;
    use feature 'say';
    
    use XML::LibXML;
    
    my $xml = q(<div class="c1"><span class="c2"><b class="c3"/></span></div>);
    
    my $doc = XML::LibXML->load_xml(string => $xml);
    
    my @hier;
    
    my ($node) = $doc->findnodes('//b');  # only first such node assigned
    
    unshift @hier, join '.', $node->nodeName, $node->getAttribute('class');
    
    while (my $parent = $node->parentNode) {
        last if $parent->nodeType == XML_DOCUMENT_NODE;  # top, <?xml ...    
    
        unshift @hier, join '.', $parent->nodeName, $parent->getAttribute('class');
        $node = $parent;
    }
    
    say for @hier;
    

    getAttribute 方法在 XML::LibXML::Element 类中。

    【讨论】:

      猜你喜欢
      • 2020-08-05
      • 2021-07-29
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多