Replace Double Quotes Within Attributes only in XML : C#

守給你的承諾、 提交于 2019-12-20 07:47:43

问题


I've this string which will be part of an XML/XML Node:

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

I need only the attribute quotes to be escaped so that it becomes

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

I'm using C#, .NET 2.0.


回答1:


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());
        }
    }
}


来源:https://stackoverflow.com/questions/37176682/replace-double-quotes-within-attributes-only-in-xml-c-sharp

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