I'...">

Right or wrong way to search in an XML element using XMLSearch?

Given the following XML:

<cfsavecontent variable="xml"> <root> <parent> <child>I'm the first</child> <child>Second</child> <child>3rd</child> </parent> <parent> <child>Only child</child> </parent> <parent> <child>I'm 10</child> <child>I'm 11!</child> </parent> </root> </cfsavecontent> 

Is this the best way to loop over each parent and then extract all the children from that parent?

 <cfset xml = XMLParse(Trim(xml))> <cfset parents = XMLSearch(xml, "//parent")> <cfloop array="#parents#" index="parent"> <cfset parent = XMLParse(parent)><!--- Is this needed? ---> <cfset children = XMLSearch(parent, "//child")> <cfloop array="#children#" index="child"> <cfoutput>#child.XmlText#</cfoutput> </cfloop> </cfloop> 

I ask because I could never extract all the children from the current XML element.

"It is necessary?" the comment underlines the line I added to make the processing line work. But is it possible to delete this line and somehow change the "XMLSearch (parent," // child ")" to get only children from the current "parent"?

Thanks.

+6
coldfusion xpath
source share
1 answer
 <cfset parent = XMLParse(parent)><!--- Is this needed? ---> 

No no. This is even a performance penalty, because you are creating a new DOM this way.

You get an array of XML nodes from XmlSearch() (why else would you use a <cfloop array... ?). This means that they must be equivalent:

 <!-- new CF8 syntax --> <cfloop array="#parents#" index="parent"> <cfdump var="#parent#"> </cfloop> <!-- old syntax --> <cfloop from="1" to="#ArrayLen(parents)#" index="i"> <cfdump var="#parents[i]#"> </cfloop> 

To create a ColdFusion fame context when searching for a node, you need to do:

 XMLSearch(parent, ".//child") -------------------^ 

If you start an XPath expression with "//" , ColdFusion obviously looks for the entire document to which the node belongs, not just the node descendants.

But if you are interested in outputting all <child> elements from a document, why not do this:

 <cfset children = XMLSearch(xml, "//child")> 
+8
source share

All Articles