我需要创建将多个Xelements连接成一个的方法。 我创建了以下方法:
static void DoStuff(string IP, string login, string password, string port)
{
CommonMethods cm = new CommonMethods();
WebClient webClient = new WebClient();
XElement output = null;
try
{
webClient = cm.ConnectCiscoUnityServerWebClient(IP, login, password);
int rowsPerPage = 100;
int pageNumber = 1;
Console.WriteLine("Getting logins from " + IP);
do
{
Console.WriteLine("Downloading " + pageNumber + " page");
string uri = @"https://" + IP + ":" + port + "/vmrest/users?bla&rowsPerPage=" + rowsPerPage + "&pageNumber=" + pageNumber;
Stream stream = webClient.OpenRead(uri);
output = XElement.Load(stream);
pageNumber++;
}
while (output.HasElements);
Console.WriteLine(output);
}
catch (Exception ex)
{
cm.LogErrors(ex.ToString(), System.Reflection.MethodBase.GetCurrentMethod().Name.ToString());
}
}
但在Do While循环中,输出被覆盖。能否请您提供一些解决方案,将输出连接成一个?
答案 0 :(得分:1)
您在每次迭代时覆盖output
元素的值。而是创建结果元素并在每次迭代时向其添加新元素:
CommonMethods cm = new CommonMethods();
WebClient webClient = new WebClient();
XElement output = null;
try
{
webClient = cm.ConnectCiscoUnityServerWebClient(IP, login, password);
int rowsPerPage = 100;
int pageNumber = 1;
Console.WriteLine("Getting logins from " + IP);
XElement result = new XElement("result"); // will hold results
do
{
Console.WriteLine("Downloading " + pageNumber + " page");
string uri = @"https://" + IP + ":" + port +
"/vmrest/users?bla&rowsPerPage=" +
rowsPerPage + "&pageNumber=" + pageNumber;
Stream stream = webClient.OpenRead(uri);
output = XElement.Load(stream);
result.Add(output); // add current output to results
pageNumber++;
}
while (output.HasElements);
Console.WriteLine(result);
}
catch (Exception ex)
{
cm.LogErrors(ex.ToString(), MethodBase.GetCurrentMethod().Name.ToString());
}
结果元素可以是第一个加载的output
元素。然后,您可以对下一个元素执行一些查询,并将结果添加到结果元素。如果没有看到你正在使用的数据,很难说清楚。