How to make XML::XPath ignore namespaces?


D

David Karr

I'm trying to use XML::XPath to extract content from XML documents. The documents are specified with namespaces, but I want to use XPath expressions without namespaces. As far as I can tell, I had this working perfectly fine in two different scripts.

It seems like sometime today, the behavior of XML::XPath has changed with respect to this. I don't see what I could have changed that has made this behavior change.

I can get some manual tests to work, if I almost fully specify namespaces, using a call to "set_namespace()" in the script (hardcoding the prefix I expect to use) and specifying the prefix in the XPath expression.

Again, I'm pretty sure I had this working yesterday, without calling "set_namespace()" in the script, or specifying prefixes in the XPath expressions.

If I don't add that "set_namespace()" call and specify prefixes in the expression, I just get empty nodesets from my queries.

I tried setting "$XML::XPath::Namespaces" to zero before I create the first XPath object, but that doesn't seem to make any difference.

The following is a simple script I pipe XML into:
--------------------
#! /bin/perl
use XML::XPath;
use XML::XPath::XMLParser;
use Getopt::Long;

$| = 1;

my $opt_file;
GetOptions("f|file=s" => \$opt_file);

$XML::XPath::Namespaces = 0;

my $xpath;
if ($opt_file ne '') {
$xpath = XML::XPath->new(filename => $opt_file);
}
else {
$xpath = XML::XPath->new(ioref => \*STDIN);
}

while (my $expr = shift @ARGV) {
my $nodeset = $xpath->find($expr);
if ($nodeset) {
if ($opt_file ne '') {
print $opt_file . ":\n";
}
my $node;
for $node ($nodeset->get_nodelist) {
print $node->string_value() . "\n";
}
}
}
------------------

Here's a sample command line:

% echo "<ns3:abc xmlns:ns3=\"xxx\"><ns3:def>ghi</ns3:def></ns3:abc>" | xpathtext "//def"

I would hope to get "ghi" from this, but I'm currently getting nothing.
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top