0

我在这里问是否有任何方法可以将变量放在 C# 中的“@”字符串中。这样以下代码中的 id 可以更改。

        string xml = @"
        <S>
          <child id='1'/>
          <child id='2'>
            <grandchild id='3' />
            <grandchild id='4' />
          </child>
        </S>";
4

4 回答 4

3

不是直接的(C# 没有插值),但您可以将 @-string 传递给string.Formator string.Concat。(或者,对于受虐狂来说,Regex.Replace

于 2012-07-03T04:12:55.757 回答
3

看看 string.Format 方法

var result = string.Format(@"<S> 
          <child id='{0}'/> 
          <child id='{1}'> 
            <grandchild id='{2}' /> 
            <grandchild id='{3}' /> 
          </child> 
        </S>", id1, id2, id3, id4);
于 2012-07-03T04:13:07.880 回答
2

您可以使用 string.Format:

string.Format(@"<S>
          <child id='{0}'/>
          <child id='{1}'>
            <grandchild id='3' />
            <grandchild id='4' />
          </child>
        </S>", childId1, childId2);
于 2012-07-03T04:14:24.257 回答
2

使用 string.Format() 在运行时将值插入到您的字符串中。有关它的更多信息可以在MSDN上找到。

    string xml = string.Format(@"
    <S>
      <child id='{0}'/>
      <child id='{1}'>
        <grandchild id='{2}' />
        <grandchild id='{3}' />
      </child>
    </S>", id1, id2, id3, id4);

虽然这不是创建 XML 的推荐方法,因为您必须确保您插入的任何值都针对其位置正确转义,但只要您严格插入数值,这应该不是问题。

于 2012-07-03T04:18:33.353 回答