Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

XML::LibXML namespaces

Status
Not open for further replies.

MacTommy

Programmer
Feb 26, 2007
116
0
0
NL
What do I have to do to have e.g. findnodes() work again when I am parsing XML that has a namespace involved..?!?

If I run this code it works fine (returns 2 fields):
Code:
#!/usr/bin/perl

use strict;

use XML::LibXML;

my $sTestXml = <<TEST;
<?xml version="1.0" encoding="UTF-8"?>
<someRoot>
    <someField/>
    <someField>
        <someValue nr="001">Bla bla</someValue>
        <someValue nr="002">Blo blo</someValue>
    </someField>
</someRoot>
TEST

my $oParser = XML::LibXML->new();
my $oTree = $oParser->parse_string($sTestXml);

my @aEntities = $oTree->documentElement->findnodes('someField');
print "Amount of fields: " . scalar(@aEntities) . "\n";

However, if I change the root element to
Code:
<someRoot xmlns="[URL unfurl="true"]http://www.bla.com/bla.xsd"[/URL] xmlns:xsi="[URL unfurl="true"]http://www.w3.org/2001/XMLSchema-instance"[/URL] xsi:schemaLocation="[URL unfurl="true"]http://www.bla.com/bla.xsd">[/URL]
it won't run anymore.

I am clearly missing something about namespaces here, but I am quit at loss just what it is..?!?
 
[1] The someRoot and the rest live in the default namespace of [ignore][/ignore]. To apply findnodes(), you still need to make it explicit via some freely named prefix defined through setNamespace method.

[2] The schemaLocation setting is incorrect. It is formed by two components, the namespace and the schema path (supposing it is the ...bla.xsd, see below [3]).

[3] This should be more correct.
[tt]
#!/usr/bin/perl

use strict;

use XML::LibXML;

my $sTestXml = <<TEST;
<?xml version="1.0" encoding="UTF-8"?>
<someRoot [ignore]xmlns=" xmlns:xsi="[/ignore] xsi:schemaLocation="[red][ignore][/ignore][/red] [ignore][/ignore]">
<someField/>
<someField>
<someValue nr="001">Bla bla</someValue>
<someValue nr="002">Blo blo</someValue>
</someField>
</someRoot>
TEST

my $oParser = XML::LibXML->new();
my $oTree = $oParser->parse_string($sTestXml);
[blue]$oTree->documentElement->setNamespace("[ignore][/ignore]","ns");
my @aEntities = $oTree->documentElement->findnodes('[red]ns:[/red]someField');[/blue]
print "Amount of fields: " . scalar(@aEntities) . "\n";
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top