Select Xml Node using Linq to XML

前端 未结 4 1488
遥遥无期
遥遥无期 2020-12-19 07:40

my Xml file :




        
相关标签:
4条回答
  • 2020-12-19 08:09

    Your problem is that Descendents and Where return an IEnumerable<XElement> not a single XElement which is what you're after. You can fix this like this:

    XElement toEdit = doc.Descendants("ArrayOfCustomer")
                         .Descendants("Customer")
                         .Where(x => Guid.Parse(x.Descendants("CustomerId").Single().Value) == customer.CustomerId)
                         .FirstOrDefault();
    
    0 讨论(0)
  • 2020-12-19 08:09

    I would restructure your query like this:

     XElement toEdit = doc.Descendants("Customer")
                          .Where(x => (Guid)x.Element("CustomerId") == customer.CustomerId)
                          .FirstOrDefault();
    
    0 讨论(0)
  • 2020-12-19 08:20

    You are not casting x you are casting x.Descendants(). x.Descendants() returns a collection, hence the plural method semantic. Off the top of my head you should be able to do x.Descendants("CustomerId").FirstOrDefault() as XElement

    0 讨论(0)
  • 2020-12-19 08:24
    XElement toEdit = (from c in doc.Descendants("Customer")
         where Guid.Parse(c.Value) == customer.CustomerId
         select c).SingleOrDefault();
    
    0 讨论(0)
提交回复
热议问题