ColdFusion 9替换第n次出现的HTML标记

时间:2012-08-11 19:43:20

标签: regex coldfusion html-parsing coldfusion-9

我将以下HTML存储在ColdFusion 9中的变量中。我需要在第4个</tr>之后插入一个新的表行。即在提交按钮之前。

<form name="form1" id="form1" action="" method="post">
    <table>
    <tr style="visibility:hidden;display:none;"><td> <input type="hidden" id="ref1" name="ref1" value="1" > </td></tr> 
    <tr style="visibility:hidden;display:none;"><td> <input type="hidden" id="ref2" name="ref2" value="2" > </td></tr> 
    <tr>
        <th style="text-align:left;">Name&nbsp;*&nbsp;</th>
        <td><input type="text" name="foo" id="foo" size="30" maxlength="50" value=""></td>
    </tr>
    <tr>
        <th title="Please enter plain text or HTML." style="cursor:help;text-align:left;">Comment&nbsp;*&nbsp;</th>
        <td><textarea name="bar" id="bar" cols="40" rows="10" ></textarea></td>
    </tr>
    <tr>
        <th colspan="1"></th>
        <td>
            <input style="width:80px" type="submit" value="Submit">
            <input style="width:80px" type="button" value="Cancel">
        </td>
    </tr>
</table>

ReReplace似乎是要走的路,但我无法正确使用正则表达式。另一个选择是拆分字符串并使用我的新HTML在中间重建它。任何建议将不胜感激。

2 个答案:

答案 0 :(得分:5)

正则表达式是错误的工具 - 你想要一个HTML解析器。

以下是使用JSoup

执行此操作的方法
<cfsavecontent variable="InputHtml">
    [insert code from question]
</cfsavecontent>

<cfsavecontent variable="NewRow">
    <tr><th>whatever</th><td>stuff</td></tr>
</cfsavecontent>

<!--- Read "Creating Objects From Jar Files" --->
<cfset jsoup = createObject('java','org.jsoup.Jsoup') />

<cfset HtmlDom = jsoup.parse(InputHtml) />

<cfset HtmlDom.select('tr:eq(4)').after( NewRow ) />

<cfoutput>
    <pre>#XmlFormat(HtmlDom.body().html())#</pre>
</cfoutput>

您可以在JSoup Selector API

中查看支持哪些选择器的详细信息

如果您不知道/关心表格中有多少行,您可以...

HtmlDom.select('table>tbody').append( NewRow )

...只是在最后添加新行。


从Jar文件创建对象

如果你复制并粘贴它,上面的代码很可能不会立即生效,因为你的服务器不知道JSoup - 你需要下载Jar文件并把它放在合理的位置。

对于CF9,您需要将jsoup-1.6.3.jar复制到{coldfusion} / lib目录中,然后重新启动服务器。

对于CF10,您可以在Application.cfc(as described here)中使用this.JavaSettings将其放置在其他位置。

对于Railo和OpenBD,您可以将JAR文件的位置指定为第三个参数,例如:

<cfset jsoup = createObject('java','org.jsoup.Jsoup','lib/jsoup-1.6.3.jar') />

答案 1 :(得分:1)

我建议使用jQuery执行此操作:

​$(document).ready(function(){

   $($('form tr')[3]).after('<tr><td>row</tr></tr>');

});​

更容易。