加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 有条件地转义特殊的xml字符

发布时间:2020-12-15 08:41:08 所属栏目:百科 来源:网络整理
导读:我已经环顾了很多但是却找不到只能转义特殊 XML字符的内置.Net方法: ,,,’和“ 如果它不是标签. 例如,采用以下文本: Test bbold/b iitalic/i Tag index="0" / 我希望它转换为: Testamp; bbold/b iitalic/i lt;Tag index="0" / 请注意,标签不会被转义.我基
我已经环顾了很多但是却找不到只能转义特殊 XML字符的内置.Net方法:
<,>,&,’和“
如果它不是标签.

例如,采用以下文本:

Test& <b>bold</b> <i>italic</i> <<Tag index="0" />

我希望它转换为:

Test&amp; <b>bold</b> <i>italic</i> &lt;<Tag index="0" />

请注意,标签不会被转义.我基本上需要将此值设置为XmlElement的InnerXML,因此必须保留这些标记.

我已经研究了实现我自己的解析器并使用StringBuilder来尽可能地优化它,但它可能变得非常讨厌.

我也知道可以接受的标签可以简化事情(仅限:br,b,i,u,blink,flash,Tag).此外,这些标签可以是自闭标签

(e.g. <u />)

或容器标签

(e.g. <u>...</u>)

解决方法

注意:这可能是优化的.这只是我为你快速敲门的事情.另请注意,我没有对标签本身进行任何验证.它只是寻找包含在尖括号中的内容.如果在标签内找到尖括号,它也会失败(例如< sometag label =“我把>这里”>).除此之外,我认为它应该做你想要的.
namespace ConsoleApplication1
{
    using System;
    using System.Text.RegularExpressions;

    class Program
    {
        static void Main(string[] args)
        {
            // This is the test string.
            const string testString = "Test& <b>bold</b> <i>italic</i> <<Tag index="0" />";

            // Do a regular expression search and replace. We're looking for a complete tag (which will be ignored) or
            // a character that needs escaping.
            string result = Regex.Replace(testString,@"(?'Tag'&;{1}[^&;&;]*[&;]{1})|(?'Ampy'&;[A-Za-z0-9]+;)|(?'Special'[&;&;""'&;])",(match) =>
                {
                    // If a special (escapable) character was found,replace it.
                    if (match.Groups["Special"].Success)
                    {
                        switch (match.Groups["Special"].Value)
                        {
                            case "<":
                                return "&lt;";
                            case ">":
                                return "&gt;";
                            case """:
                                return "&quot;";
                            case "'":
                                return "&apos;";
                            case "&":
                                return "&amp;";
                            default:
                                return match.Groups["Special"].Value;
                        }
                    }

                    // Otherwise,just return what was found.
                    return match.Value;
                });

            // Show the result.
            Console.WriteLine("Test String: " + testString);
            Console.WriteLine("Result     : " + result);
            Console.ReadKey();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读