【问题标题】:How do I replace line breaks with valid html but not when in an html element already如何用有效的 html 替换换行符,但不是在 html 元素中
【发布时间】:2013-02-01 20:04:49
【问题描述】:

我有一些纯文本,其中包含这样的换行符:

Dear Person,\r\nHello and welcome to this example.\r\nTodo: <ul><li>item 1</li>\r\n<li>item 2</li>\r\nThanks.

我想使用 HtmlAgility 包(如果需要)来清理 Html 并用 BR 替换新的换行符,除非它们已经在 HTML 标记中(请参阅 UL 标记中的 LI)

我可以使用 regx 或 text.Replace(Environment.NewLine, "&lt;br/&gt;") 轻松替换 BR,但是如何排除它在标签中的情况?

谢谢。

【问题讨论】:

  • 我不确定您的问题描述是否合理 - 所有内容都在 HTML 中的一个元素中,并且元素可以任意嵌套(至少原则上如此)。

标签: c# html-agility-pack


【解决方案1】:

看来您只需要处理顶级 HTML 文本节点(文本节点没有子节点):

var html = "Dear Person,\r\nHello and welcome to this example.\r\nTodo: <ul><li>item 1</li>\r\n<li>item 2</li>\r\nThanks.";
var doc = new HtmlDocument();
doc.LoadHtml(html);
var textNodes = doc.DocumentNode.ChildNodes
    .OfType<HtmlTextNode>()
    .ToList();

foreach (var node in textNodes)
    node.Text = node.Text.Replace(Environment.NewLine, "<br />");

这将产生如下内容:

Dear Person,<br />Hello and welcome to this example.<br />Todo: <ul><li>item 1</li>\r\n<li>item 2</li>\r\nThanks.</ul>

【讨论】:

    【解决方案2】:
    String sentence = "Dear Person,\r\nHello and welcome to this example.\r\nTodo: <ul><li>item 1\r\nitem 2</li>\r\n<li>item 3</li>\r\nThanks.";
    String[] splits = Regex.Split(sentence, @"(<li>[^<]+</li>)");
    
    for (Int32 i = 0; i < splits.Length; ++i)
    {
        if (!splits[i].StartsWith("<li>"))
            splits[i] = splits[i].Replace("\r\n", "<br/>");
    }
    
    sentence = String.Join("", splits);
    

    另外,请勿使用 Environment.NewLine,因为它可能会有所不同,而您的字符串换行符将始终为“\r\n”。

    【讨论】:

    • 它不是专门的 LI,它可以是任何 html 元素。
    • 所以使用这个正则表达式:@"(]+>[^]+>)"
    猜你喜欢
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 2015-09-16
    • 2022-11-14
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多