[英]Escaping double quotes within String.Format in C#
我正在嘗試獲取要用雙引號引起來的Parameter元素的'Id'屬性。 我首先嘗試簡單地忽略引號,這是我嘗試實現的第一件事:
buffer = String.Format("{0}" + "<Parameter Id=" + "{1}" + ">" + "{2}" + "</Parameter>", buffer, id, param);
通過上面的代碼,我將其弄回來,如您所見,出現了轉義字符以及引號:
<Conquest><User>ArchElf</User><Token>0123456789012345678901234567890</Token><Command>validate</Command><Parameter Id=\"1\">Gemstone3</Parameter>
我的第二次嘗試是基於我在IRC上收到的建議,另一個是建議我可以使用““”來獲取報價,ala:
buffer = String.Format("{0}" + "<Parameter Id=" + """ + "{1}" + """ + ">" + "{2}" + "</Parameter>", buffer, id, param);
此方法僅在最終結果中產生文字'“'字符串:
<Conquest><User>ArchElf</User><Token>0123456789012345678901234567890</Token><Command>validate</Command><Parameter Id="1">Gemstone3</Parameter>
無奈之下,我繼續前進,只是在字符串中添加了文字雙引號。
我這樣做是因為我在本《代碼項目》文章中讀到,我需要擔心轉義的String.Format中唯一的字符是花括號,並且(驚訝,令人驚訝)這甚至都無法編譯,使用WITH和WITHOUT前面的@ 。 向我大喊一堆錯誤,包括:
只能將賦值,調用,遞增,遞減,等待和新對象表達式用作語句; 預期)預期...等等
在此問題上的任何幫助將不勝感激。 我知道這一定是我想念的瑣碎小事,最好的難題。 :/
這是整個BuildCommand方法:
public string BuildCommand(string _command, string[] _parameters = null)
{
int id = 1;
string buffer = String.Format("<Conquest><User>"+"{0}"+"</User><Token>"+"{1}"+"</Token><Command>"+"{2}"+"</Command>", _playerName, _token, _command);
if (_parameters != null)
{
foreach (string param in _parameters)
{
if (param.Length < 1 || param == null)
break;
buffer = String.Format("{0}" + "<Parameter Id=" + "{1}" + ">" + "{2}" + "</Parameter>", buffer, id, param);
// buffer = String.Format(@"""{0}""<Parameter Id=""{1}"">""{2}""</Parameter>", buffer, id, param);
id += 1;
}
}
您必須使用\\
轉義"
:
String.Format("\"{0}\"<Parameter Id=\"{1}\">\"{2}\"</Parameter>", buffer, id, param);
您還可以使用逐字字符串文字,然后必須使用雙引號:
String.Format(@"""{0}""<Parameter Id=""{1}"">""{2}""</Parameter>", buffer, id, param);
你可以用正確的方式做
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//<Conquest><User>ArchElf</User><Token>0123456789012345678901234567890</Token><Command>validate</Command><Parameter Id=\"1\">Gemstone3</Parameter>
string user = "ArchElf";
string token = "0123456789012345678901234567890";
string command = "validate";
int id = 1;
string value = "Gemstrone3";
XElement conquest = new XElement("Conquest");
conquest.Add(new XElement("User", user));
conquest.Add(new XElement("Token", token));
conquest.Add(new XElement("Command", command));
XElement e_parameter = new XElement("Parameter", value);
e_parameter.Add(new XAttribute("Id", id));
conquest.Add(e_parameter);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.