XML :: LibXML的文本节点父级的概念 [英] XML::LibXML's notion of a text node's parent
问题描述
这里有些奇怪.
在下面的示例中,我正在通过XPath查询(//book/isbn/text()
)访问文本节点. text()
是强制使XML::LibXML
允许我使用XML::LibXML::Text
方法的必要条件.
In the example below, I'm accessing text nodes via an XPath query ( //book/isbn/text()
). The text()
is necessary to coerce XML::LibXML
into allowing me to use the XML::LibXML::Text
methods.
但是,要到达父节点,我必须调用两次parentNode
方法以获得真正的父节点(在本例中为<book>
):
To get to the parent node though, I have to invoke the parentNode
method twice to get the true parent node (<book>
in this case):
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>
所以:
So:
- 在假设
//isbn
和//isbn/text()
是同一节点时,我对XML节点的理解是错误的,或者 - 这是
XML::LibXML
的parentNode
方法中的错误吗? ?
- is my understanding of XML nodes incorrect in assuming that
//isbn
and//isbn/text()
are the same node, or - is this a bug in
XML::LibXML
'sparentNode
method?
推荐答案
XML文档中的每个元素都是一个节点.如果该元素包含文本(例如<isbn>019328373476</isbn>
),则它是该元素的子节点(与元素相对的文本类型).
Each element in a XML document is a node. If that element contains text (e.g. <isbn>019328373476</isbn>
), then it is a child node (of type text, as opposed to element) of that element.
这不是XML :: LibXML的parentNode方法中的错误.
It is not a bug in XML::LibXML's parentNode method.
这篇关于XML :: LibXML的文本节点父级的概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!