tags:

views:

140

answers:

2

Hi All,

I am working on some Plesk integration using the XML API and I am trying to figure out how to parse the XML response that I get back. Most of the data is fine, but the Limits and Permissions are setout differently. Essentially they are set out like so:

<data>
  <limits>
    <limit>
      <name>foo</name>
      <value>bar</value>
    </limit>
    <limit>
      <name>foo2</name>
      <value>bar2</value>
    </limit>
  </limits>
</data>

How do I extract 'bar' from the xml given that I know I want the value of 'foo', but not the value of 'foo2'?

+6  A: 
<cfset my_xml = XmlParse(XMLCODE) />

<cfoutput>
1: #my_xml.data.limits[0].limit.value#
<br />2: #my_xml.data.limits[1].limit.value#
</cfoutput>
Ivo Sabev
Thanks for the help. I thought there might be a way where I didnt have to manually specify the node number (in case it gets changed at some point) but this looks to be the best answer I could find. I should probably point out that I had to move the [0] to after the limit and that I had to specify .xmlText after the value, but that may be due to me explaining the problem badly.
Ryan French
You can have a loop over the my_xml.data.limits which will give you all the limit.value values if you are looking for a way to get them all.
Ivo Sabev
+1  A: 

If you know specifically what the "name" of the limit is going to be, you can use XPath for this. What you're looking for is the "value" child node of any limit nodes where the name child node is "foo". In XPath, this looks like:

'/data/limits/limit[name = 'foo']/value'

This will return an array of nodes (since there can be multiple matches), so we need to handle the array. The whole example is:

    <cfset myXML = "
    <data>
      <limits>
        <limit>
          <name>foo</name>
          <value>bar</value>
        </limit>
        <limit>
          <name>foo2</name>
          <value>bar2</value>
        </limit>
      </limits>
    </data>
">
<!--- Parse the string into an XML Object --->
<cfset XMLDOM = xmlParse(myXML)>
<!--- Search the XML Object for specific nodes --->
<cfset nodeArray = xmlSearch(XMLDOM,"/data/limits/limit[name = 'foo']/value")>
<!--- Loop over the returned array of XML Node objects and print the XMLText (the node value) --->
<cfloop array="#nodeArray#" index="thisNode">
    <cfoutput>#thisNode.xmlText#</cfoutput>
</cfloop>
Edward M Smith