0

i am here to ask if there are any ways to put variables inside "@" Strings in C#. Such that the id in the following code, can be changeable.

        string xml = @"
        <S>
          <child id='1'/>
          <child id='2'>
            <grandchild id='3' />
            <grandchild id='4' />
          </child>
        </S>";
3
  • 1
    string.Format is your friend. Commented Jul 3, 2012 at 4:12
  • The XElement/XAttribute constructors are made to work in a similarly constructable fashion. Commented Jul 3, 2012 at 4:14
  • 1
    if you are making XML, use C#s XML facilities. Hand rolling it is just asking for trouble Commented Jul 3, 2012 at 4:17

4 Answers 4

3

take a look at the string.Format method

var result = string.Format(@"<S> 
          <child id='{0}'/> 
          <child id='{1}'> 
            <grandchild id='{2}' /> 
            <grandchild id='{3}' /> 
          </child> 
        </S>", id1, id2, id3, id4);
Sign up to request clarification or add additional context in comments.

Comments

3

Not directly (C# doesn't have interpolation), but you can pass an @-string to string.Format or string.Concat. (or, for the masochasists, Regex.Replace)

Comments

2

You can use string.Format:

string.Format(@"<S>
          <child id='{0}'/>
          <child id='{1}'>
            <grandchild id='3' />
            <grandchild id='4' />
          </child>
        </S>", childId1, childId2);

Comments

2

Use string.Format() to insert values into your string at runtime. More info about it can be found on MSDN.

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

This isn't the recommended way to create XML though since you will have to make sure that any value you insert is properly escaped for it's location but as long as you are strictly inserting numerical values this shouldn't be a problem.

2 Comments

the majority of this looks like copy/paste from other answers but +1 anyways for pointing out that its possibly unsafe
Most of the answers were written within a few minutes of the post, so no one really had time to copy 'n paste anybody. There were only Ben Voigts answer when I started writing mine and I though it lacked some explanation. When I was done others had already submitted their answers though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.