2
4

1 回答 1

3

如果我理解正确,这可能会奏效。如果不是,请在预期文本的外观之前、中间、之后清楚地显示出来。

        var nodes = doc.DocumentNode.Descendants("#text").Where(text => Regex.IsMatch(text.InnerText.Trim(), @"≤[^≥]*≥"));
        string format =
            @"<div class=""wrapper"" contenteditable=""false""><span class=""wrapper2""><div class=""myClass"">{0}</div><button type="" button"" class=""MergeCodeRemoveIcon"">×</button></span></div>";

        foreach (var htmlNode in nodes)
        {
            htmlNode.InnerHtml = string.Format(CultureInfo.InvariantCulture, format, htmlNode.InnerText.Trim().Trim(new[] { '≤', '≥' }));
        }

        return doc.DocumentNode.OuterHtml;

尝试这个:

    private static string transformFromMergeCodesToHtml(string textWithMergeCodes)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(textWithMergeCodes);

        var nodes = doc.DocumentNode.Descendants("#text").Where(text => Regex.IsMatch(text.InnerText.Trim(), @"≤[^≥]*≥"));
        string format =
            @"<div class=""wrapper"" contenteditable=""false""><span class=""wrapper2""><div class=""myClass"">$2</div><button type="" button"" class=""MergeCodeRemoveIcon"">×</button></span></div>";

        foreach (var htmlNode in nodes)
        {
            htmlNode.InnerHtml = Regex.Replace(htmlNode.InnerText.Trim(), @"(≤)([^≥]*)(≥)", format);
        }
        return doc.DocumentNode.OuterHtml;
    }

    private static string transformFromHtmlToMergeCodes(string text)
    {
        var doc = new HtmlDocument();
        doc.LoadHtml(text);
        var nodes = doc.DocumentNode.SelectNodes("//div[@class='wrapper']");
        foreach (var item in nodes)
        {
            var innerText = "≤" + item.SelectSingleNode("//div[@class='myClass']").InnerText.Trim() + "≥";
            var textNode = HtmlNode.CreateNode(innerText);
            item.ParentNode.ReplaceChild(textNode, item);
        }
        return doc.DocumentNode.InnerHtml;

    }

注意:我也更新了另一种方法!

于 2012-12-14T00:14:28.340 回答