Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

XML::Writer and namespaces

by Mr. Ed (Initiate)
on Dec 21, 2016 at 13:15 UTC ( [id://1178292]=perlquestion: print w/replies, xml ) Need Help??

Mr. Ed has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I wonder how to add namespace into my xml-attribute declaration: "xsi:nil='true'" I have to create a xml like this:

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <node1 xsi:nil="true" /> </root>
But I can't find the right way to do this. My Code:
1 #!/bin/perl 2 use strict; 3 use warnings; 4 use utf8; 5 6 use XML::Writer; 7 8 9 my $ns1 = "http://www.w3.org/2001/XMLSchema-instance"; 10 my $prefixMap = {$ns1 => "xsi"}; 11 12 my $writer = new XML::Writer( 13 OUTPUT => 'self', 14 DATA_INDENT => 3, 15 DATA_MODE => 1, 16 NAMESPACES => 1, 17 PREFIX_MAP => $prefixMap 18 ); 19 20 $writer->startTag("root"); 21 22 $writer->emptyTag("node1", ('nil' => "true")); 23 $writer->emptyTag("node3", [$ns1, "nil" => "true"]); 24 $writer->endTag("root"); 25 26 print $writer->to_string;
Gives me this:
<root> <node1 nil="true" /> <node3 xsi:nil="xmlns:xsi" http://www.w3.org/2001/XMLSchema-instanc +e="" /> </root>

1) I miss the namespace declaratione in the <root> - element

2) If I try to set the namespace on an attribute manualy like:  $writer->emptyTag("node1", ('xsi:nil' => "true")); I get an error: Attribute name 'xsi:nil' contains ':' and the writer terminates.

Is there anyone who can help me? Thanks.

Replies are listed 'Best First'.
Re: XML::Writer and namespaces
by Mr. Ed (Initiate) on Dec 21, 2016 at 13:51 UTC
    Ok, I've find out to get the namespace-declaration in the root-element: <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    I need to set $writer->forceNSDecl($ns1); before writing the first tag

    But how get I the "xsi:" - Prefix on the attribute?
      And finally ... here is the solution for issue 2) $writer->emptyTag("node", ([$ns1,"nil"] => "true")); makes my day: <node xsi:nil="true" />

      You have to read the perldoc very carefully, The NAMESPACES-section says:

      ... then the module will accept two-member array reference in the place of element and attribute names ...
      Hi, I want to ask if there is any metho other than forceNSDecl to add namespace? in case if I want to add an attribute after the namespace?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1178292]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (3)
As of 2024-04-19 20:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found