Ask Ben: Collecting And Relating Sibling XML Nodes In A ColdFusion XML Document

<!--- Create XML data. --->
<cfxml variable="xmlData">
 
	<?xml version="1.0" encoding="UTF-8" ?>
	<mainDocument>
		<informationTableData>
			<id>0001393825</id>
			<saleDataInfo>
				<sundayData>
					<saleDate>2008-10-26</saleDate>
					<saleDataList>
						<nameOfCompany>Acme Explosives</nameOfCompany>
						<start>N/A</start>
						<sold>0</sold>
						<end>N/A</end>
					</saleDataList>
					<saleDataList>
						<nameOfCompany>Beavis Inc.</nameOfCompany>
						<start>100</start>
						<sold>25</sold>
						<end>75</end>
					</saleDataList>
				</sundayData>
			</saleDataInfo>
		</informationTableData>
		<informationTableData>
			<id>2221393333</id>
			<saleDataInfo>
				<sundayData>
					<saleDate>2008-10-26</saleDate>
					<saleDataList>
						<nameOfCompany>Hot Fusion</nameOfCompany>
						<start>500</start>
						<sold>10</sold>
						<end>490</end>
					</saleDataList>
					<saleDataList>
						<nameOfCompany>Smith Cousins</nameOfCompany>
						<start>150</start>
						<sold>50</sold>
						<end>100</end>
					</saleDataList>
				</sundayData>
			</saleDataInfo>
		</informationTableData>
	</mainDocument>
 
</cfxml>
 
 
<!---
	Create a struct in which the ID values of the above XML
	document will be the keys (to which the sundayData will
	be associated).
--->
<cfset objID = {} />
 
 
<!---
	Now, let's get all of the ID fields (that have a sibling
	sundayData node). For this demo, we are going to assume
	that is a requirement:
 
	Check for sibling node "saleDataInfo" with "sundayData":
	../saleDataInfo/sundayData
--->
<cfset arrIDNodes = XmlSearch(
	xmlData,
	"//informationTableData/id[ ../saleDataInfo/sundayData ]"
	) />
 
<!--- Loop over ID nodes to add them to our index object. --->
<cfloop
	index="xmlIDNode"
	array="#arrIDNodes#">
 
	<!---
		Create an ID-based index that points to the
		sundayData node. We can easily get the ID from the
		current node; but, to get the sundayData node, we
		have to walk the tree a bit - go up to parent node,
		then back down through saleDataInfo to get to the
		taret sundayData node.
	--->
	<cfset objID[ xmlIDNode.XmlText ] =
		xmlIDNode.XmlParent.saleDataInfo[ 1 ].sundayData[ 1 ]
		/>
 
</cfloop>
 
 
<!--- Output our final ID index. --->
<cfdump
	var="#objID#"
	label="ID-Based Index Of sundayData"
	/>

For Cut-and-Paste