问题描述
我在使用 XML :: LibXML 包中的名称空间时难以理解/使用名称空间Perl.我可以成功访问元素,但不能访问属性.我有以下代码可以访问XML文件( http://pastebin.com/f3fb9d1d0 ).
I am having trouble understanding / using name spaces with XML::LibXML package in Perl. I can access an element successfully but not an attribute. I have the following code which accesses an XML file (http://pastebin.com/f3fb9d1d0).
my $tree = $parser->parse_file($file); # parses the file contents into the new libXML object.
my $xpc = XML::LibXML::XPathContext->new($tree);
$xpc->registerNs(microplateML => 'http://moleculardevices.com/microplateML');
然后我尝试访问一个名为common-name的元素和一个名为name的属性.
I then try and access an element called common-name and an attribute called name.
foreach my $camelid ($xpc->findnodes('//microplateML:species')) {
my $latin_name = $camelid->findvalue('@name');
my $common_name = $camelid->findvalue('common-name');
print "$latin_name, $common_name" ;
}
但是仅打印拉丁文名称(@name
),而不是普通名称.我在做什么错?我如何也可以打印出通用名称?
But only the latin-name (@name
) is printing out, the common-name is not. What am I doing wrong and how can I get the common-name to print out as well?
在这种情况下,@name是做什么的?我假设它是一个数组,应该将属性放入一个数组中,因为可以有多个属性,但是元素(如common-name)不应该是因为应该只有一个?
What does the @name do in this case? I presume it is an array, and that attributes should be put into an array as there can be more than one, but elements (like common-name) should not be because there should just be one?
我一直在关注以下示例: http ://www.xml.com/pub/a/2001/11/14/xml-libxml.html 此处: http://perl-xml.sourceforge.net/faq/#namespaces_xpath,并尝试使其示例骆驼脚本与我的名称空间配合使用,从而使名称空间变得怪异.
I've been following the examples here: http://www.xml.com/pub/a/2001/11/14/xml-libxml.htmland here: http://perl-xml.sourceforge.net/faq/#namespaces_xpath, and trying to get their example camel script working with my namespace, hence the weird namespace.
推荐答案
确保您的XML文件有效,然后使用$node->getAttribute("someAttribute")
访问属性.
Make sure you XML file is valid then use $node->getAttribute("someAttribute")
to access attributes.
@name是属性名称.您可以在findnodes()中使用它来指定具有给定属性集的元素.例如.像这样的路径:
@name is a attribute name. You'd use it in findnodes() to specify elements with a given attribute set. Eg. a path like:
//camelids/species[@name="Camelus bactrianus"]/
这是一个简单/人为的示例:
Here is a simple/contrived example:
#!/usr/bin/perl -w
use XML::LibXML;
my $parser = XML::LibXML->new();
my $doc = $parser->parse_file('/Users/castle/Desktop/animal.xml');
my $xc = XML::LibXML::XPathContext->new( $doc->documentElement() );
$xc->registerNs('ns', 'http://moleculardevices.com/microplateML');
my @n = $xc->findnodes('//ns:species');
foreach $nod (@n) {
print "A: ".$nod->getAttribute("name")."\n";
my @c = $xc->findnodes("./ns:common-name", $nod);
foreach $cod (@c) {
print "B: ".$cod->nodeName;
print " = ";
print $cod->getFirstChild()->getData()."\n";
}
}
输出为:
perl ./xmltest.pl
A: Camelus bactrianus
B: common-name = Bactrian Camel
这篇关于如何在Perl中从XML :: LibXML访问属性和元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!