XDocument Descendants of Descendants

时间:2011-03-01 04:34:33

标签: c# .net linq linq-to-xml

<Tickets>
<Extract_Date>2011-02-25 00:00:00</Extract_Date>
<Incidents>
  <Ticket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Ticket_Number>INC000000578057</Ticket_Number>
    <Status>
      <Value>Cancelled</Value>
    <Reason>Cancelled by user</Reason>
  </Status>
</Ticket>

我可以通过以下方式获得ticket_number:

var q1 = from c in xmlDoc.Descendants("Ticket")
                   select new
                   {
                       Ticket_Number = (string)c.Element("Ticket_Number"),
                   };

如何获得理由?

2 个答案:

答案 0 :(得分:3)

这应该有效:

var q1 = from c in xmlDoc.Descendants("Ticket")
    select new
    {
        Ticket_Number = (string)c.Element("Ticket_Number"),
        Reason = (string)c.Element("Status").Element("Reason")
    };

答案 1 :(得分:2)

//if you have exactly one <Ticket> with exactly one <Reason>
string strReason = xmlDoc.Descendants("Ticket").Single()
    .Descendants("Reason").Single().Value;

//if you have one or multiple <Ticket> elements, 
//each with exactly one <Reason> element
string[] astrReasons = xmlDoc.Descendants("Ticket")
    .Select(ticket => ticket.Descendants("Reason").Single().Value).ToArray();

//if you have one or multiple <Ticket> elements, 
//each with one or multiple <Reason> elements
string[] astrReasons2 = xmlDoc.Descendants("Ticket")
    .SelectMany(ticket => ticket.Descendants("Reason")
    .Select(reason => reason.Value)).ToArray();