通过XML节点循环

本文关键字:循环 节点 XML 通过 | 更新日期: 2023-09-27 18:04:52

我正在以XML格式从网站中提取一些数据,当没有连续节点时,它可以正常工作,但当有节点时,我很难弄清楚如何循环使用它们。我得到的数据看起来像。。。

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

如何循环浏览并读取每个节点的数据?我现在的代码如下。。。

    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;
    }

票务类。。。

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;
}

通过XML节点循环

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();

你可以试试这个代码。如果你试图取回一个不存在的元素的值,它会抛出一个异常。