質問

I was just going through certain code...I wanted to know what the following code means

string format = "//User[UserName=\"{0}\" and EncryptPassword=\"{1}\"]";
string xpath = String.Format( format, userName, password );    

xpath is later used to create xPathNodeIterator object. I dont quite understand how String.Format is used and which node will the XPathNodeIterator will be iterating through if I iterate?

役に立ちましたか?

解決

Read the details of String.Format. It

Replaces each format item in a specified string with the text equivalent of a corresponding object's value.

it means that xpath will contain format string where {0} in the format string will be replaced with value of username and {1} will be replaced with value of password

Assuming that

string userName = "Ehsan";
string password = "Password";
string format = "//User[UserName=\"{0}\" and EncryptPassword=\"{1}\"]";
string xpath = String.Format(format, userName, password);  

Xpath will be equivalent to

//User[UserName="Ehsan" and EncryptPassword="Password"]

他のヒント

It is roughly equivalent to the code

string xpath = "//User[UserName=\"" + userName.ToString() + "\" and EncryptPassword=\"" + password.ToString() + "\"]";

String.Format just lets you replace placeholders in test strings easily and optionally add additional formatting.

It just means "use userName and password for {0} and {1} respectively, in the string "//User[UserName=\"{0}\" and EncryptPassword=\"{1}\"]";

That will give you the resulting string:

"//User[UserName=\"John\" and EncryptPassword=\"correctHorseBatteryStaple\"]"

(assuming the value of userName was John, and... well, you can guess the password).

Assume:

userName = "Peter"
password = "abc123"

Your xpath will be:

String.Format(format, userName, password)
String.Format("//User[UserName=\"{0}\" and EncryptPassword=\"{1}\"]", "Peter", "abc123")

As the {0} is replaced by userName, "Peter", and {1} is replaced by passowrd, "abc123", your xpath becomes:

//User[UserName="Peter" and EncryptedPassword="abc123"]

The thing to remember is that all those {0}, {1}, etc will be replaced by strings that follow.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top