Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract XML name/value pairs from different nodes in Coldfusion

Tags:

coldfusion

xml

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 http://download1.parallels.com/Plesk/PPP9/Doc/en-US/plesk-9.2-api-rpc/index.htm?fileName=28788.htm>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'?

like image 769
Ryan French Avatar asked Feb 27 '23 05:02

Ryan French


2 Answers

<cfset my_xml = XmlParse(XMLCODE) />

<cfoutput>
1: #my_xml.data.limits[0].limit.value#
<br />2: #my_xml.data.limits[1].limit.value#
</cfoutput>
like image 74
Ivo Sabev Avatar answered May 01 '23 19:05

Ivo Sabev


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>
like image 37
Edward M Smith Avatar answered May 01 '23 19:05

Edward M Smith