When you write $bus_url = $BusUrl->item( 0 )->getChildAtIndex( 0 )->getData(); you apply a method (getData) to an undef value ($BusUrl->item( 0 )->getChildAtIndex( 0 )), hence the error. You should first check whether $BusUrl has children, throught the appropriately named hasChildNodes method.

The easiest way would be to add a sub that would return the text of the element or undef (or the empty string if it's more convenient for you). While you're at it you could also improve that sub to make it resistent to extra whitespace in the elements: if you only look at the first child of the BusinessUrl element, chances are that one day it will be a line return, with the real data on the following line (and child). Using XPath (either by switching to XML::LibXML or by using XML::DOM::XPath (which is a shameless plug)) will give you a better chance at making your code less dependent on the formating of the XML data.

You use the following (untested) code by calling my $bus_url= field( $contact, 'BusinessUrl'). Note that it is still not great, as extra comments in the data for example would be returned as part of the content of the element.

sub field { my( $parent, $tag)= @_; my @elts= $parent->getElementsByTagName( $tag); return unless( @elts); my $elt= $elts[0]; return unless( $elt->hasChildNodes); return join( '', map { $_->getData } $elt->getChildNodes); }

In reply to Re: use XML::DOM - what to do with empty tags? by mirod
in thread use XML::DOM - what to do with empty tags? by kevyt

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.