Pergunta

I am pulling some data from a website in XML format and it works fine when there are not consecutive nodes, but I am having trouble figuring out how to loop through them when there is. The data that I get looks something like...

 <whmcsapi> 
  <action>gettickets</action> 
  <numreturned>1</numreturned> 
  <tickets> 
   <ticket>  
    <tid>557168</tid> 
    <name><![CDATA[Array]]></name> 
    <subject><![CDATA[Test Ticket]]></subject> 
    <message><![CDATA[This is a test ticket>
   <ticket>
   <ticket>
    <tid>557168</tid> 
    <name><![CDATA[Array]]></name> 
    <subject><![CDATA[Test Ticket]]></subject> 
    <message><![CDATA[This is a test ticket>
   <ticket>

How can I loop through and read the data from each node? My code right now is the following...

    public List<Ticket> Get_Tickets()
    {
        Dictionary<string, string> args = new Dictionary<string, string>();
        args.Add("status", "All Active Tickets");

        string data = Get_Data("gettickets", args);
        XDocument doc = XDocument.Parse(data);

        //var support_tickets = doc.Descendants("ticket").Select(ticket => new
        List<Ticket> support_tickets = (from x in doc.Descendants("ticket") select new Ticket
        {
            ID = x.Element("id").Value,
            TicketID = x.Element("tid").Value,
            DeptID = x.Element("deptid").Value,
            UserID = x.Element("userid").Value,
            Name = x.Element("name").Value,
            Email = x.Element("email").Value,
            Subject = x.Element("subject").Value,
            Message = x.Element("message").Value,
        }).ToList();

        return support_tickets;
    }

The Ticket class...

public class Ticket
{
    public string ID;
    public string TicketID;
    public string DeptID;
    public string UserID;
    public string Name;
    public string Email;
    public string CC;
    public string Subject;
    public string Message;
    public string Status;
    public string Priority;
    public DateTime Date;
    public DateTime LastResponse;
    public IPAddress IP;
}
Foi útil?

Solução

List<Ticket> supportTickets = 
    (from x in doc.Descendants("ticket")
     select new Ticket
     {
         ID = x.Element("id").Value,
         TicketID = x.Element("tid").Value,
         DeptID = x.Element("deptid").Value,
         UserID = x.Element("userid").Value,
         Name = x.Element("name").Value,
         Email = x.Element("email").Value,
         Subject = x.Element("subject").Value,
         Message = x.Element("message").Value,
     }).ToList();

You can try this code. If you try to get back the value of a Element which doesn't exist, it will throw an exception.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top