在XML属性中替换双引号:C# [英] Replace Double Quotes Within Attributes only in XML : C#
本文介绍了在XML属性中替换双引号:C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
string a =< Node一个= \ a\[\ \/>中;
我只需要转义属性引号,使其成为
a =Node a = \a& qout; [& qout; \/>;
我正在使用C#,.NET 2.0。
解决方案
您发现的链接是正确的,它只需要适应C#。
这是转换:
using System;
使用System.Collections.Generic;
使用System.Text;
命名空间RegEx
{
类程序
{
static void Main(string [] args)
{
string text =<节点a = \a \[\\b = \b \[\\/>< Node2 a = \a\\ \\[\\b = \b \[\\/>;
string regEx =(\\s + [\\w:.-] + \\s * = \\s * \)(([^ \] *)((\ )((?\\s + [\\w:.-] + \\s * = \\s * \ | \\s *(:???/ | \\)GT;))[^ \ ] *)*)\;
StringBuilder sb = new StringBuilder();
int currentPos = 0;
foreach(System.Text.RegularExpressions.Match匹配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());
}
}
}
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.
解决方案
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());
}
}
}
这篇关于在XML属性中替换双引号:C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文