how to represent default null namespace using Perl XML::LibXML
Here is my code to generate the given XML.
my $doc = XML::LibXML::Doc开发者_运维百科ument->new( '1.0', 'utf-8' );
my $nodeBroadsoft = $doc->createElementNS ('C', 'BroadsoftDocument');
$nodeBroadsoft->setNamespace ('http://www.w3.org/2001/XMLSchema-instance', 'xsi', 0);
$nodeBroadsoft->setAttributeNS('', 'protocol', 'OCI' );
$doc->addChild ($nodeBroadsoft);
my $nodeSession = $doc->createElementNS ('', "sessionId");
$nodeSession->setNamespace ("", undef, 0);
$nodeSession->appendTextNode ($sessionID);
$nodeBroadsoft->addChild ($nodeSession);
my $nodeCommand = $doc->createElementNS ('', "command");
$nodeCommand->setNamespace ("", undef, 0);
$nodeBroadsoft->addChild ($nodeCommand);
$nodeCommand->setAttributeNS ('http://www.w3.org/2001/XMLSchema-instance', 'type', 'AuthenticationRequest');
my $nodeUserId = $doc->createElementNS ('', 'userId');
$nodeUserId->appendTextNode ('automation');
$nodeCommand->addChild ($nodeUserId);
When I am running this program it's generating following XML
<?xml version="1.0" encoding="utf-8"?>
<BroadsoftDocument xmlns="C" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" protocol="OCI">
<sessionId>1231313313133131</sessionId>
<command xsi:type="AuthenticationRequest">
<userId>automation</userId>
</command>
</BroadsoftDocument>
and I need the following:
<BroadsoftDocument protocol="OCI" xmlns="C" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<sessionId xmlns="">31436753,1298637565495</sessionId>
<command xsi:type="AuthenticationRequest" xmlns="">
<userId>automation</userId>
</command>
</BroadsoftDocument>
The only difference is in the sessionId and command elements. The generated XML is missing the "xmlns=""" for these two tags.
I am trying to use the following function but it's not working.
$nodeSession->setNamespace ("", undef, 0);
$nodeCommand->setNamespace ("", undef, 0);
As I understand (as a beginner to XML), I need the default namespace having null value for sessionId and command elements. Please help
Very late to the party here, I'm learning about XML namespaces as an un-billed work-related digression- was a good exercise for me.
If it is OK to have a space instead of the empty string to represent the null namespace, this works:
my $sessionID=1231313313133131;
my $nodeSession = $doc->createElementNS (" ", "sessionId");
# No need to call setNamespace
$nodeSession->appendTextNode ($sessionID);
Result:
<sessionId xmlns=" ">1231313313133131</sessionId>
I also tried resorting to Perl hackery, using an object that is true in bolean & numeric contexts yet stringifies to the empty string. It didn't have the desired effect. For giggles your can view that attempt at PerlMonks.
精彩评论