我正在以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;
}
Ticket类......
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;
}
答案 0 :(得分:4)
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();
您可以尝试使用此代码。如果你试图找回一个不存在的Element的值,它将抛出异常。