Parsing XML String in C#

て烟熏妆下的殇ゞ 提交于 2019-12-18 19:09:16

问题


I have looked over other posts here on the same subject and searched Google but I am extremely new to C# NET and at a loss. I am trying to parse this XML...

<whmcsapi version="4.1.2"> 
 <action>getstaffonline</action> 
 <result>success</result> 
 <totalresults>1</totalresults> 
 <staffonline> 
  <staff> 
   <adminusername>Admin</adminusername> 
   <logintime>2010-03-03 18:29:12</logintime> 
   <ipaddress>127.0.0.1</ipaddress> 
   <lastvisit>2010-03-03 18:30:43</lastvisit> 
  </staff> 
 </staffonline> 
</whmcsapi>

using this code..

    XDocument doc = XDocument.Parse(strResponse);

    var StaffMembers = doc.Descendants("staff").Select(staff => new
    {
        Name = staff.Element("adminusername").Value,
        LoginTime = staff.Element("logintime").Value,
        IPAddress = staff.Element("ipaddress").Value,
        LastVisit = staff.Element("lastvisit").Value,
    }).ToList();

    label1.Text = doc.Element("totalresults").Value;

    foreach (var staff in StaffMembers)
    {
        listBox1.Items.Add(staff.Name);
    }

I have printed out the contents of strResponse and the XML is definitely there. However, when I click this button, nothing is added to the listBox1 or the label1 so I something is wrong.


回答1:


Add Root here to start navigating from the root element (whmcsapi):

string label1_Text = doc.Root.Element("totalresults").Value;


来源:https://stackoverflow.com/questions/4703252/parsing-xml-string-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!