worik has asked for the wisdom of the Perl Monks concerning the following question:
Given that I wish to build an XML node that may contain plain text like:
<owner> John Smith </owner>
Or it may contain a child node like:
<owner> <href>http://johnsmith.com</href> </owner>
And the text/node that is to be added is obtained from a function that can return either, is there an XML::LibXML function that I can call that will call appendTextNode in the first case and appendChildNode in the second? If there is I cannot find it.
What I have:
#!/usr/bin/perl -w use strict; use XML::LibXML; # The XML Document my $DOC = XML::LibXML->createDocument( "1.0", "UTF-8" ); # Set the root my $root = $DOC->createElement('owner'); $DOC->setDocumentElement($root); sub createOwner { if(rand() < 0.5){ return "John Smith"; }else{ my $ret = XML::LibXML::Element->new('href'); $ret->appendTextNode('http://johnsmith.com'); return $ret; } } my $owner = &createOwner(); if(ref($owner) eq 'XML::LibXML::Element'){ $root->appendChild($owner); }else{ $root->appendTextNode($owner); } print $DOC."\n";
This returns either:
<?xml version="1.0" encoding="UTF-8"?> <owner>John Smith</owner>
OR
<?xml version="1.0" encoding="UTF-8"?> <owner><href>http://johnsmith.com</href></owner>
What I want
#!/usr/bin/perl -w use strict; use XML::LibXML; # The XML Document my $DOC = XML::LibXML->createDocument( "1.0", "UTF-8" ); # Set the root my $root = $DOC->createElement('owner'); $DOC->setDocumentElement($root); sub createOwner { if(rand() < 0.5){ return "John Smith"; }else{ my $ret = XML::LibXML::Element->new('href'); $ret->appendTextNode('http://johnsmith.com'); return $ret; } } my $owner = &createOwner(); $root->appendChild($owner); print $DOC."\n";
This will have an error:
XML::LibXML::Node::appendChild() -- nNode is not a blessed SV referencein the case that the plain string is returned. I wish to avoid the testing in the calling function.
Worik
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: XML::LibXML creating nodes with a string OR a node
by choroba (Cardinal) on Jun 07, 2015 at 22:41 UTC | |
by worik (Sexton) on Jun 07, 2015 at 23:00 UTC | |
by Anonymous Monk on Jun 07, 2015 at 23:31 UTC | |
by worik (Sexton) on Jun 08, 2015 at 21:38 UTC | |
by Anonymous Monk on Jun 08, 2015 at 04:50 UTC | |
by worik (Sexton) on Jun 08, 2015 at 21:38 UTC | |
by Anonymous Monk on Jun 07, 2015 at 22:48 UTC | |
|
Re: XML::LibXML creating nodes with a string OR a node
by Anonymous Monk on Jun 07, 2015 at 22:59 UTC |