我的Perl脚本中的findnodes语句有什么问题? [英] What's wrong with this findnodes statement in my Perl's script?
问题描述
我有一个简单的xml文件,如下所示:
I have a simple xml file that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<microplateDoc xmlns="http://moleculardevices.com/microplateML">
<camelids>
<species name="Camelus bactrianus">
<common-name>Bactrian Camel</common-name>
<physical-characteristics>
<mass>450 to 500 kg.</mass>
<appearance>
Blah blah blah
</appearance>
</physical-characteristics>
</species>
</camelids>
</microplateDoc>
我正在尝试使用以下perl脚本读取物种名称:
I'm trying to read the species names with the following perl script:
use XML::LibXML;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file('/Users/johncumbers/Documents/7_Scripts/Perl/XML_to_MySQL/simplified_camelids.xml');
my $xc = XML::LibXML::XPathContext->new( $doc->documentElement() );
$xc->registerNs('ns', 'http://moleculardevices.com/microplateML');
#loop through to find species nodes
my @n = $xc->findnodes('*/species'); #was */species
foreach $nod (@n) {
print "A: ".$nod->getAttribute("name")."\n";
my @c = $nod->findnodes('./common-name');
}
但是我无法找到任何节点.您能提供帮助并告诉我为什么它不起作用吗?什么是查找perl功能的最佳网站,以便我自己尝试解决这一问题?我如何获取脚本来告诉我它在做什么,因为当前的输出什么都没有.非常感谢.
But I am failing to get find any nodes. Are you able to help and tell me why it is not working please? What is the best website to look up perl functions so that I can try and trouble shoot this myself? How can I get the script to tell me what it is doing, as the output at the moment is just nothing. Many thanks.
推荐答案
You've associated a namespace prefix with the document, but your XPath syntax doesn't use it.
my @n = $xc->findnodes('//ns:species');
应该做的工作.
没有前缀,您将无法匹配.此外,*/species
路径将仅与当前上下文(即文档的顶层)中的子项匹配.使用//species
将在文档中找到所有species
元素.如果这对您不起作用(因为该元素出现在您不想匹配的文档中的其他上下文中),请使用
Without the prefix you'll not match. Also the */species
path will only match children in the current context (i.e. the top level of the document). Using //species
will find all species
elements in the document. If that doesn't work for you (because the element appears in some other context in the document you don't want to match) use
/*/*/ns:species
因为该元素是顶层的大孙子".
as the element is a 'great grandchild' of the top level.
又一个 XPath 参考.
这篇关于我的Perl脚本中的findnodes语句有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!