开发者

Update xml file with ColdFusion

I have an xml file that needs to updated. The user wants to be able to select the year and amount. What is the best way?

Thanks

<root>
<SGA>
<Year>2008</Year>
<Amt>940</Amt>
</SGA>
<SGA>
<Year>2009</Year>
<Amt>980</Amt>
</SGA开发者_JS百科>
<SGA>
<Year>2010</Year>
<Amt>1000</Amt>
</SGA>  
</root>


You probably want to use the 'contains' operator (Alejandro points out that that's not a strict match) a match in XPath. To execute XPath in Coldfusion, use the xmlSearch function on an XML object. The normalize-space() function trims leading and trailing whitespace (fixing, for instance the CR in the 2010 year node).

Because the XPath is matching the year node directly, we use the '/..' to fetch the year node's parent. This is if you wanted to operate on any of the other sibling nodes to year (for instance if there was also a "quantity" node or something).

<cfxml variable="foo">
<root>
<SGA>
<Year>2008</Year>
<Amt>940</Amt>
</SGA>
<SGA>
<Year>2009</Year>
<Amt>980</Amt>
</SGA>
<SGA>
<Year>2010
</Year>
<Amt>1000</Amt>
</SGA>  
</root>
</cfxml>


<cfset targetYear=" 2010">
<cfset newAmount=2000>

<cfdump var="#foo#">

<!--- returns an array of matching nodes. --->
<cfset bar = xmlSearch(foo,"/root/SGA/Year[normalize-space()='#trim(targetYear)#']/..")>

<cfdump var="#bar#">

<cfset bar[1].Amt.xmlText = newAmount>

<cfdump var="#foo#">

In a real application, you'd want to iterate over the results of the xmlSearch (bar in this case) as an array, as there exists the possibility to get 0 or more then 1 result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜