仅在 XML 中替换属性内的双引号:C#

2024-02-16

我有这个字符串,它将成为 XML/XML 节点的一部分:

string a = "<Node a=\"a\"[\"\"/>";

我只需要转义属性引号,使其变为

a= "Node a=\"a&qout;[&qout;\"/>";

我正在使用 C#、.NET 2.0。


您找到的链接是正确的,它只需适应 C# 即可。

这是转换:

using System;
using System.Collections.Generic;
using System.Text;

namespace RegEx
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "<Node a=\"a\"[\"\" b=\"b\"[\"\"/>   <Node2 a=\"a\"[\"\" b=\"b\"[\"\"/>";
            string regEx = "(\\s+[\\w:.-]+\\s*=\\s*\")(([^\"]*)((\")((?!\\s+[\\w:.-]+\\s*=\\s*\"|\\s*(?:/?|\\?)>))[^\"]*)*)\"";
            StringBuilder sb = new StringBuilder();

            int currentPos = 0;
            foreach(System.Text.RegularExpressions.Match match in System.Text.RegularExpressions.Regex.Matches(text, regEx)) {
                sb.Append(text.Substring(currentPos, match.Index - currentPos));
                string f = match.Result(match.Groups[1].Value + match.Groups[2].Value.Replace("\"", "&quot;")) + "\"";
                sb.Append(f);
                currentPos = match.Index + match.Length;
            }

            sb.Append(text.Substring(currentPos));

            Console.Write(sb.ToString());
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅在 XML 中替换属性内的双引号:C# 的相关文章

随机推荐