简体   繁体   中英

Using Linq for XDocument Element value

I have the following in an XML example:

<custreply>
   <customer cid="1234">
     <ack id="6000" error="false">
       <info>
          <custgroup>A</custgroup>
          <message>cust created</message>
       </info>
       <info>
          <custgroup>A</custgroup>
          <message>cust setup created</message>
       </info>
     </ack>
   </customer>
   <customer cid="5678">
     <ack id="7000" error="true">
       <error>
          <class>B</class>
          <message>over the limit</message>
       </error>
     </ack>
   </customer>
</custreply>

Then I have XDocument and Linq that works great for the following two values I need ack id and ack error:

XDocument CustResponse = XDocument.Load('path');

var custAck = from c in CustResponse.Root.DescendantsAndSelf("ack")
                                   select new { CustId = c.Attribute("id").Value, Error = c.Attribute("error").Value
                                   };

What I also need is in the select a ErrorMessage and for the error shown in the above XML if the error="true" the "message" element value. How can I get that? I would also take the error false message if possible just the first message element in the first info if any easier but I need mostly the error element message in my results don't really need the message of the error false.

Thanks all

Try following :

            XDocument CustResponse = XDocument.Load(FILENAME);

            var custAck = CustResponse.Root.DescendantsAndSelf("ack")
                .Select(c => new { 
                    CustId = (string)c.Attribute("id"), 
                    Error = (string)c.Attribute("error"),
                    messages = c.Descendants("message").Select(x => (string)x).ToList()

            }).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM