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
In reply to XML::LibXML creating nodes with a string OR a node by worik
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |