Jump to content

How to handle empty XML fields in JS


iandunn
 Share

Recommended Posts

I'm using JavaScript to retrieve info from an XML file, but if any of the fields are empty I get this error:

Error: xmlDocument.getElementsByTagName("address2Title")(0).firstChild has no propertiesSource File: http://localhost/contactManager/Line: 47
Here's an example of the XML file:
<contact>  <id>2</id>  <firstName>First Name</firstName>  <lastName>Last Name</lastName>  <address1Title>Home</address1Title>  <address1>101 Blah St</address1>  <city1>Dayton</city1>  <state1>Ohio</state1>  <zipCode1>45402</zipCode1>  <address2Title/>  <address2/>  <city2/>  <state2/>  <zipCode2/>  <homePhone>9375559407</homePhone>  <cellPhone>9375556845</cellPhone>  <workPhone/>  <birthday>01311978</birthday></contact>

And here's the relevant JS code

document.getElementById("contactInfo").innerHTML = xmlDocument.getElementsByTagName('firstName').item(0).firstChild.nodeValue +xmlDocument.getElementsByTagName('lastName').item(0).firstChild.data +xmlDocument.getElementsByTagName('address1Title').item(0).firstChild.data +xmlDocument.getElementsByTagName('address1').item(0).firstChild.data +xmlDocument.getElementsByTagName('city1').item(0).firstChild.data +xmlDocument.getElementsByTagName('state1').item(0).firstChild.data +xmlDocument.getElementsByTagName('zipCode1').item(0).firstChild.data +xmlDocument.getElementsByTagName('address2Title')(0).firstChild.nodeValue +xmlDocument.getElementsByTagName('address2').item(0).firstChild.data +xmlDocument.getElementsByTagName('city2').item(0).firstChild.data +xmlDocument.getElementsByTagName('state2').item(0).firstChild.data +xmlDocument.getElementsByTagName('zipCode2').item(0).firstChild.data +xmlDocument.getElementsByTagName('homePhone').item(0).firstChild.data +xmlDocument.getElementsByTagName('cellPhone').item(0).firstChild.data +xmlDocument.getElementsByTagName('workPhone').item(0).firstChild.data +xmlDocument.getElementsByTagName('birthday').item(0).firstChild.data;

Is there a way to access the field that won't cause an error if it's empty, or is there a way to check if it's empty before trying to use it?

Link to comment
Share on other sites

var fields = [ "firstName" , "lastName" , "addressTitle" , "address1" , "city1" ];var content = ""for(i = 0; i < fields.length; i++){ if(xmlDocument.getElementsByTagName(fields[i]).item(0).firstChild.data){   content += xmlDocument.getElementsByTagName(fields[i]).item(0).firstChild.data }}document.getElementById("contactInfo").innerHTML = content

Something like that?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...