1

i have xml file like Below and Device class and i want get List<Device> from my xml file how i can do that by linq

            XDocument loaded = XDocument.Load(SharedData.CONFIGURATION_FULL_PATH);
            var q = loaded.Descendants("device").Select(c => c);

but of course this code Does not work

<?xml version="1.0" encoding="utf-8"?>
<settings>
<device>
  <username>aa</username>
  <AgentName>aa</AgentName>
  <password>aa</password>
  <domain>aa</domain>
</device>
<device>
  <username>bb</username>
  <AgentName>bb</AgentName>
  <password>bb</password>
  <domain>bb</domain>
</device>
<device>
  <username>cc</username>
  <AgentName>cc</AgentName>
  <password>cc</password>
  <domain>cc</domain>
</device>

</settings>

2 Answers 2

4
List<Device> devices = new List<Device>(loaded.Descendants("Device")
                                             .Select(e =>
                                               new Device(e.Element("username").Value,
                                                          e.Element("AgentName").Value,
                                                          e.Element("password").Value,
                                                          e.Element("domain").Value
                                                         )));
Sign up to request clarification or add additional context in comments.

Comments

0

You could do this:

var devices =
    loaded
        .Descendants("Device")
        .Select(e => new Device(
            e.Element("username").Value,
            e.Element("AgentName").Value,
            e.Element("password").Value,
            e.Element("domain").Value))
        .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.