我正在尝试使用 Html Agility Pack 突出显示 html 字符串中的文本。我可以用
替换文本,但是当我替换文本时,span 标记周围的空白消失了。例如,如果文本是“此文本将突出显示”
,则结果为“此文本将突出显示” 和 span 标记之前的空格消失了。这会将跨度之前和之后的单词与跨度文本合并。我只是做一个这样的递归循环:
- 获取第一个子节点
- 如果节点是
#text
,则
- ,如果节点有
node.InnerHtml = InnerText.Replace(search_term, span_code)
子节点转到步骤 1
- 转到下一个兄弟节点,然后转到步骤 1
然后我得到 HtmlDocument
的 InnerHtml
作为结果。我尝试在 之前和
之后添加空格,但它删除了它们。我尝试了 HtmlDocument.OptionWriteEmptyNodes = true;
它也不起作用。在创建 HtmlDocument
之前和获取 html 字符串之后,我用空格替换了所有 "\n"
和 "\t"
字符,但它没有都不影响。
使用 Html Agility Pack 时如何保留空白?
I'm trying to highlight a text in the html string by using Html Agility Pack. I'm able to replace text with <span class="highlight">
, but when I replace the text, the white space around the span tag is disappeared. For example, if the text is "This text will be highlighted"
, it results as "This text will be<span class='highlighted'>highlighted</span>"
, and white space gone before the span tag. This merges the words before and after the span with the span text. I simply do a recursive loop like that:
- Get first child node
- if the node is
#text
, than node.InnerHtml = InnerText.Replace(search_term, span_code)
- if node has child node goto step 1
- goto next sibling then go to step 1
Then I get the InnerHtml
of the HtmlDocument
as a result. I tried put space before <span
and after </span>
, but it removed them. I tried HtmlDocument.OptionWriteEmptyNodes = true;
it didn't work either. I replaced all "\n"
and "\t"
chars with a space before creating HtmlDocument
and after getting the html string, and it didn't affect neither.
How can I preserve the white space when using Html Agility Pack?
发布评论
评论(1)
实际上
HtmlDocument.OptionWriteEmptyNodes = true;
做了我想要的。我现在意识到了。Actually
HtmlDocument.OptionWriteEmptyNodes = true;
did what I want. I realized now.