Replace Double Quotes Within Attributes only in XML : C#

这一生的挚爱 提交于 2019-12-02 13:15:57

The link you found was correct, it just had to be adapted to C#.

Here is the conversion :

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());
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!