在XML中需要插入自己的字符串,但是发现&<>"这些字符无法替换掉,使用正常的Replace没有效果,网上也没有找到合适的。并且由于是控制台程序,无法引用NET类,经过查询MSDN得到些启发,写下这个转换方法,以供参考。如果有更好的方法可以共享下!
#region XML转义字符处理
/// <summary>
/// XML转义字符处理
/// </summary>
public static string ConvertXml(string xml)
{
xml = (char)1 + xml; //为了避免首字母为要替换的字符,前加前缀
for (int intNext = 0; true; )
{
int intIndexOf = xml.IndexOf("&", intNext);
intNext = intIndexOf + 1; //避免&被重复替换
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + "&" + xml.Substring(intIndexOf + 1);
}
}
for (; true; )
{
int intIndexOf = xml.IndexOf("<");
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + "<" + xml.Substring(intIndexOf + 1);
}
}
for (; true; )
{
int intIndexOf = xml.IndexOf(">");
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + ">" + xml.Substring(intIndexOf + 1);
}
}
for (; true; )
{
int intIndexOf = xml.IndexOf("\"");
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + """ + xml.Substring(intIndexOf + 1);
}
}
return xml.Replace(((char)1).ToString(), "");
}
#endregion
/// <summary>
/// XML转义字符处理
/// </summary>
public static string ConvertXml(string xml)
{
xml = (char)1 + xml; //为了避免首字母为要替换的字符,前加前缀
for (int intNext = 0; true; )
{
int intIndexOf = xml.IndexOf("&", intNext);
intNext = intIndexOf + 1; //避免&被重复替换
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + "&" + xml.Substring(intIndexOf + 1);
}
}
for (; true; )
{
int intIndexOf = xml.IndexOf("<");
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + "<" + xml.Substring(intIndexOf + 1);
}
}
for (; true; )
{
int intIndexOf = xml.IndexOf(">");
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + ">" + xml.Substring(intIndexOf + 1);
}
}
for (; true; )
{
int intIndexOf = xml.IndexOf("\"");
if (intIndexOf <= 0)
{
break;
}
else
{
xml = xml.Substring(0, intIndexOf) + """ + xml.Substring(intIndexOf + 1);
}
}
return xml.Replace(((char)1).ToString(), "");
}
#endregion