简体   繁体   中英

Linq on Complex XML

Hi I Have the following XML

<Feed>
<Control>
        <Username>Fnol13</Username>
        <Password>12345</Password>          
</Control>
<Repairer>
        <RepairerName>Test</RepairerName>
        <RepairerAddress>Test</RepairerAddress>
        <RepairerTelephone>Test</RepairerTelephone>
</Repairer>
</Feed>

And a Model Class Containing following Properties

[Serializable]
public  class Job {

    public string Username { get; set; }

    public string Password { get; set; }

    public string Reference { get; set; }

    public string RepairerAddress { get; set; }

    public string RepairerTelephone { get; set; }


}   

I am using following Linq Query to Extract Data from XML

var results = from job in xmlDoc.Descendants("Control")
                      select new Job {
                          Username = (string)job.Element("Username").Value,
                          Password = (string)job.Element("Password").Value


                      };
// Here I want to add as well Descendants("Repairer") using same query

        return results.ToList();

Problem is that can return Descendants("Control") However I would like to get also Descendants("Repairer") and return in a same list as my model is showing. Could you please help me to write Linq Query and I am confirming you I am very new in Linq.

Your Model Job looks confusing to me because you may have multiple Control & Repairer nodes in which case it should map to a collection. Anyways for current XML I assume you need the elements of first Repairer node, you can achieve it like this:-

var results = from job in xmlDoc.Root.Elements("Control")
              let Repairer = job.Parent.Elements("Repairer").FirstOrDefault()
              select new Job
                   {
                      Username = (string)job.Element("Username"),
                      Password = (string)job.Element("Password"),
                      RepairerName = (string)Repairer.Element("RepairerName"),
                      RepairerAddress = (string)Repairer.Element("RepairerAddress"),
                      RepairerTelephone = (string)Repairer.Element("RepairerTelephone")
                   };

Also, note (string)job.Element("Username") will give you the node value. There is no need to call the Value property.

Update:

You can use XDocument when working with LINQ-to-XML:-

XDocument xmlDoc = XDocument.Load(XMLpath);

您可以做类似的事情-

Reference = (string)job.Parent.Descendants("Repairer").FirstOrDefault().Element("RepairerAddress").Value;

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