Reputation: 10503
I am using ColdFusion. I am trying to access an attribute of an element and can't quite figure out how to do it. The name of the element is Package. The name of the attribute is ID. I need to get the Package ID.
<cfset Packages = xmlSearch(MyXMLDoc, '/IntlRateV2Response/Package')>
I have uploaded an image of the id that I am trying to get at.
http://evikjames.com/SteinAir/xml.jpg
I swear I have tried every possible combination and looked everywhere for the answer. But, luck. Can you help?
I have tried the solutions offered below. I can't get it to work for me. It seems that I successfully put the value of the Package ID into a variable, but it's just an array. I can't seem to access it in the array. Here's my error:
Complex object types cannot be converted to simple values.
Here's the code I am using:
<cfset PackageID = xmlSearch(MyXMLDoc, 'Package/Package/@ID[i]')>
<cfset Observations = xmlSearch(MyXMLDoc, " Package/Observations[i]")>
I can output Observations, but I can't output PackageID.
What's up?
Upvotes: 2
Views: 1154
Reputation: 28873
Update: Fixed case of attribute name per comments
If only the "id" is needed, Abel's approach is slicker. But if you need to process other information as well, either of these should work. Just watch for case sensitivity issues.
<cfxml variable="str">
<IntlRateV2Response>
<Package ID="123">a</Package>
<Package ID="456">b</Package>
<Package ID="789">c</Package>
</IntlRateV2Response>
</cfxml>
<cfset MyXMLDoc = xmlParse(str)>
<cfset packages = xmlSearch(MyXMLDoc, '/IntlRateV2Response/Package')>
<cfloop array="#packages#" index="pack">
<cfoutput>
#pack.xmlAttributes["ID"]# OR
#pack.xmlAttributes.ID#
</cfoutput>
</cfloop>
Upvotes: 1
Reputation: 57197
If you follow this guide, the following should work for you (essentially, this is XPath syntax):
<cfset IdAttributes= xmlSearch(MyXMLDoc, '/IntlRateV2Response/Package/@ID')>
Upvotes: 5