JLo*_*ott 0 c# xml string concatenation
这是一个愚蠢的问题,也许它搞砸了我,因为它是在当天晚些时候,但为什么下面的代码在我尝试使用双引号时也会加入反斜杠:
C#:
private List<string> dataList;
private int ShowAuditLogForPrimaryID { get; set; }
private string xmlString;
private DataSet _dataSet;
SqlDataReader reader = sqlCommand.ExecuteReader();
dataList = new List<String>();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
string rdr = reader[i].ToString();
dataList.Add(rdr);
string Name = reader.GetName(i);
xmlString = xmlString + Name + "=" + " " + "\"" + dataList[i].ToString() + "\"" + " ";
Console.WriteLine(xmlString);
}
Run Code Online (Sandbox Code Playgroud)
它包括字符串中的反斜杠,它不允许我的xml阅读器能够读取它.
我感谢任何帮助.提前致谢!
除了在编写变量之前使用变量这一事实外,您的代码看起来还不错.如果要查看其中的内容,请尝试将字符串打印到控制台; 如果你在调试器中查看它,调试器将尝试再次转义引号.
更一般地说,尽量避免编写这样的代码.您可以使代码更清晰的一些方法是:
首先,明智地使用常量:
const string quote = "\"";
const string space = " ";
const string equals = "=";
xmlString = Name + equals + space + quote + dataList[i].ToString() + quote + space;
Run Code Online (Sandbox Code Playgroud)
现在这更容易阅读,因为你没有那里的所有引用.
其次,呼叫ToString
是不必要的.ToString
如有必要,字符串连接逻辑将自动调用.
第三,String.Format
明智地使用.
const string xmlAttributeFormat = "{0} = \"{1}\" ";
string xmlString = String.Format(xmlAttributeFormat, Name, dataList[i]);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
623 次 |
最近记录: |