Search code examples
c#xmldocument

XDocument search syntax for nodes


I am trying to read the following xml with XDocument.

<?xml version="1.0" encoding="utf-8"?>
<Project>
  <ID />
  <ProjectName>sdgsdf</ProjectName>
  <ProjectDate>12-01-0001</ProjectDate>
  <ProjectToPost>
    <Website>
      <ID>4</ID>
      <Type>Web</Type>
    </Website>
    <Website>
      <ID>5</ID>
      <Type>Web</Type>
    </Website>
  </ProjectToPost>
  <ProjectToRead>
    <Website>
      <ID>6</ID>
      <Type>Web2</Type>
    </Website>
    <Website>
      <ID>7</ID>
      <Type>Web2</Type>
    </Website>
  </ProjectToRead>
</Project>

I can get the results from 1st level with :

 XDocument xdocument = XDocument.Load(filenamepath);
            IEnumerable<XElement> Project = xdocument.Elements();
            foreach (var item in Project)
            {
                txt_1= item.Element("ID").Value;
                txt_2= item.Element("ProjectName").Value;                

                foreach (var item2 in item.Element("WebsitesToPost"))
                {

                }
            }

But then I try to go for nested elements I am not getting the syntax I should follow. Thank you in advance.


Solution

  • It can be something like this

    var projectName = (string)xdocument.Root.Element("ProjectName");
    
    var webSites =  xdocument.Root.Element("ProjectToPost")
                        .Elements("Website")
                        .Select(w => new
                        {
                            ID = (int)w.Element("ID"),
                            Type = (string)w.Element("Type"),
                        })
                        .ToList();