Skip to main content
January 30, 2008
Question

XML: Variable # nodes problem...

  • January 30, 2008
  • 2 replies
  • 296 views
I have nodes in my XML file that look like this:
<?xml...
<Listings xmlns...
<Listing>
<name>John Doe</name>
<address format="simple">
<component name="addr1">155 Main Street</component>
<component name="city">New York</component>
<component name="province">NY</component>
<component name="postal_code">99999</component>
</address>
<phone type="main">(555) 555-5555</phone>
<phone type="fax">(444) 444-4444</phone>
</Listing>
</Listings>

The problem is, what if all 4 address lines aren't there, and what if they don't send the Fax or any phone number. With simpler XML elements, I'm able to do stuff like this and it works:

<cfif NOT structKeyExists(mydoc.listings.listing , "name")>
<cfoutput>Record #i#: Name doesn't exist!</cfoutput><br>
<cfset mydoc.listings.listing
.name = XmlElemNew(mydoc,"name")>
<cfset mydoc.listings.listing .name.XmlText = "Unknown">
</cfif>

If "name" isn't in the file, it sets it to "Unknown".

But I can't get this code to work for the more complicated structures like address and phone above. If I do something like the following, it says the phone isn't present, even though it is:

<cfif NOT structKeyExists(mydoc.listings.listing
,"phone[1]")>
<cfoutput>Record #i#: Phone_main doesn't exist!</cfoutput><br>
<cfset mydoc.listings.listing .phone[1].xxx = XmlElemNew(mydoc,"xxx")>
<cfset mydoc.listings.listing
.phone[1].xxx.XmlText = "0">
</cfif>

Basically the problem is, if I don't insert a node, then Coldfusion throws an exception when I try to put it in a query:

<cfset temp = QuerySetCell(storequery, "phone_main",
#mydoc.listings.listing .phone[1].XmlText#, #i#)>

Maybe there's a better work-around for the problem than inserting nodes for missing nodes? I tried using <cfparam> with default values, no luck there. That throws an exception too. Also if I try using XmlSearch and the item is missing, it throws an exception.

Any help with this would be greatly appreciated.
Thanks!

Mike
This topic has been closed for replies.

2 replies

Inspiring
January 31, 2008
> Still not having any luck with this, and my problems are compounding as I find
> more of these complex XML statements in the feed. Any help to get on the right
> track with this would be greatly appreciated.

Read the docs on xmlSearch():
http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=functions_t-z_24.html

And get up to speed with xpath:
http://www.zvon.org/xxl/XPathTutorial/General/examples.html
http://www.w3schools.com/xpath/

--
Adam
January 31, 2008
Still not having any luck with this, and my problems are compounding as I find more of these complex XML statements in the feed. Any help to get on the right track with this would be greatly appreciated.