0

I have a variable "StudentID" which is an int, I need to convert to a string then pass it to string as a string.

This is what I have so far:

int StuID = Convert.ToString("StudentID");

string ReturnXML = "<Student=\"StuID\" />";

So if the "StudentID" variable were equal to 12345, I need the ReturnXML to look like this:

<Student="12345">

Any suggestions?

1
  • 2
    <Student="12345"> is not valid xml, it should be <Student ID="12345"> Commented Jun 1, 2011 at 19:04

7 Answers 7

3

I took the liberty to alter the XML a bit, to make it valid.

int studentId = 42;
string returnXml = string.Format(@"<Student id=""{0}"" />", studentId);
// returnXml will be '<Student id="42" />'

If you want the Student element itself to have the student id value, you probably want to put the value inside the element:

string returnXml = string.Format(@"<Student>{0}</Student>", studentId);
// returnXml will be '<Student>42</Student>'
Sign up to request clarification or add additional context in comments.

Comments

3

Since this is homework I don't want to give you the answer directly, however, look at Int32.ToString() for the string conversion. To build the return XML please look up String.Format() function.

1 Comment

+1 for not actually giving a solution; I missed the homework tag.
1

You can convert an int to an Xml Element like this:

XElement student = new XElement("Student", new XAttribute("Id", stuId));
string returnXml = student.ToString();
// returnXml will be '<Student Id="42" />'

Your XML is not valid, I added an Id tag. The advantage of XElement versus the string format in the other answers is, that you can create complex xml-trees and use queries to filter.

Comments

0

Why not just use string.Format:

int stuId = 12345;
var returnXml = string.Format("<Student id=\"{0}\" />", stuId);

Comments

0
string StuID = StudentID.ToString();

string ReturnXML = "<Student=\"" + StuID + "\" />";

Comments

0

If you need to replace variable name with its value, you can do

int stuId = 1;
string ReturnXML = string.Format("<Student=\"{0}\" />",stuId.ToString());

Comments

0

this should work:

string StuID = StudentID.ToString();

string ReturnXML = "<Student ID=\"" + StuID + "\" />";

2 Comments

this doesn't work at all! ToString returns a string, not an int. You better use string format like in the other samples than add strings with +.
@slfan: it's supposed to be a string, I put int as the type of StuID by mistake.

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.