问题
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("\"", """)) + "\"";
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