3

这里似乎有些奇怪。

在下面的示例中,我通过 XPath 查询 ( //book/isbn/text()) 访问文本节点。有text()必要强迫XML::LibXML我使用这些XML::LibXML::Text方法。

但是,要到达父节点,我必须调用该parentNode方法两次才能获得真正的父节点(<book>在这种情况下):

use strict;
use warnings;
use XML::LibXML;

my $xml = XML::LibXML->new->parse_string( << 'MAIN' );
  <library>
    <book>
      <title>Perl Best Practices</title>
      <author>Damian Conway</author>
      <isbn>0596001738</isbn>
      <pages>542</pages>
      <image src="http://www.oreilly.com/catalog/covers/perlbp.s.gif"
             width="145" height="190" />
    </book>
    <book>
      <title>Perl Cookbook, Second Edition</title>
      <author>Tom Christiansen</author>
      <author>Nathan Torkington</author>
      <isbn>0596003137</isbn>
      <pages>964</pages>
      <image src="http://www.oreilly.com/catalog/covers/perlckbk2.s.gif"
             width="145" height="190" />
    </book>
  </library>
MAIN

foreach my $isbn ( $xml->findnodes( '//book/isbn/text()' ) ) {

    # Do something with $isbn->setData()

    my $book = $isbn->parentNode->parentNode;  # My daddy's daddy is my daddy?
    print $book->toString;
}

输出

<book>
      <title>Perl Best Practices</title>
      <author>Damian Conway</author>
      <isbn>0596001738</isbn>
      <pages>542</pages>
      <image src="http://www.oreilly.com/catalog/covers/perlbp.s.gif" width="145" height="190"/>
    </book><book>
      <title>Perl Cookbook, Second Edition</title>
      <author>Tom Christiansen</author>
      <author>Nathan Torkington</author>
      <isbn>0596003137</isbn>
      <pages>964</pages>
      <image src="http://www.oreilly.com/catalog/covers/perlckbk2.s.gif" width="145" height="190"/>
    </book>

所以:

  • 假设//isbn//isbn/text()是同一个节点,我对 XML 节点的理解是否不正确,或者
  • XML::LibXML这是'sparentNode方法中的错误吗?
4

1 回答 1

2

XML 文档中的每个元素都是一个节点。如果该元素包含文本(例如<isbn>019328373476</isbn>),则它是该元素的子节点(文本类型,与元素相反)。

这不是 XML::LibXML 的 parentNode 方法中的错误。

于 2011-08-28T17:52:20.987 回答