仅在XML中替换属性中的双引号:C#
我有这个字符串,它将成为XML / XML节点的一部分:
string 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 = " "; 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()); } } }