开发者

converting a int variable to a string and passing as a string

I have a variable "StudentID" which is an int, I nee开发者_开发知识库d 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?


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>'


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.


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.


Why not just use string.Format:

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


string StuID = StudentID.ToString();

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


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

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


this should work:

string StuID = StudentID.ToString();

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜