Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re^4: Namespaced XML::LibXML XPath query (not a bug)

by grantm (Parson)
on Oct 24, 2008 at 00:52 UTC ( #719213=note: print w/replies, xml ) Need Help??

in reply to Re^3: Namespaced XML::LibXML XPath query (not a bug)
in thread Namespaced XML::LibXML XPath query

OK, here's a standalone example that might help:

#!/usr/bin/perl use strict; use warnings; use XML::LibXML; use XML::LibXML::XPathContext; my $parser = XML::LibXML->new(); my $doc = $parser->parse_fh(\*DATA); my $xc = XML::LibXML::XPathContext->new( $doc->documentElement() ) +; $xc->registerNs( xapi => 'xmlapi_1.0' ); foreach my $ccc ($xc->findnodes('//xapi:ccc')) { print "Found a ccc\n"; foreach my $d2 ( $xc->findnodes('./xapi:d2', $ccc) ) { print " d2 element contained: '" . $d2->to_literal . "'\n"; } if(my $animal = $xc->findvalue('./xapi:zoo/xapi:critter', $ccc) ) +{ print " The mystery animal is '$animal'\n"; } } exit; __DATA__ <aaa xmlns="xmlapi_1.0"> <bbb> <ccc> <d1>blah d1a</d1> <d2>blah d2a</d2> <d3>blah d3a</d3> <zoo> <critter>Monkey</critter> </zoo> </ccc> <ccc> <d1>blah d1b</d1> <d2>blah d2b</d2> <d3>blah d3b</d3> <zoo> <critter>Giraffe</critter> </zoo> </ccc> </bbb> </aaa>

So the key point is that if you want to match an element that has a namespace (explicit via a prefix or inherited from a parent element) then you must include the namespace when you refer to the element in your XPath expression.

When matching a namespace, the only thing that matters is the URI. The prefix used in the source document (if there was one) is irrelevant. The prefix used in your code when you register the namespace URI is also irrelevant. What matters is that your XPath query includes a prefix that has been registered to associate it with the same URI as the namespace declared in the source document.

Replies are listed 'Best First'.
Re^5: Namespaced XML::LibXML XPath query (not a bug)
by jbfamilly (Initiate) on Oct 24, 2008 at 03:42 UTC
    I had tried:
    foreach my $d2 ( $ccc->findnodes('./xapi:d2') ) {
    instead of:
    foreach my $d2 ( $xc->findnodes('./xapi:d2', $ccc) ) {

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://719213]
[Corion]: Ah, you are not on Windows, so disregard my opinion.
[vedagiri89]: in centos, how to fix this.
[choroba]: You have to find out why it happened. Was there an OS update?
[vedagiri89]: that is what i can't getting solution
[vedagiri89]: recently purchased centos server and doing migration of app
[choroba]: did you copy any dependencies?
[choroba]: all XS code needs to be recompiled

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2018-06-19 11:24 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (113 votes). Check out past polls.