一旦您在 tdom 节点上调用
delete
,它就不再存在,因此如果您随后尝试使用它,自然会收到错误。
一种方法:对于每个
br
节点,创建一个新的处理指令节点,然后用它替换 br
节点(这首先需要获取该节点的父节点)。你的循环将如下所示:
foreach node [$root getElementsByTagName br] {
set lb [$doc createProcessingInstruction linebreak ""]
[$node parentNode] replaceChild $lb $node
# replaceChild moves the old node to the document fragment list;
# just get rid of it completely since we're not going to reuse it
$node delete
}
修改后的程序打印出来
Input:
<p>Line with following newline<br>Line with two following newlines<br><br>Line with no following newline</p>
Output:
<html><p>Line with following newline<?linebreak ?>Line with two following newlines<?linebreak ?><?linebreak ?>Line with no following newline</p></html>