簡體   English   中英

Select Xml 節點使用 Linq 到 XML

[英]Select Xml Node using Linq to XML

我的 Xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCustomer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Customer>
        <CustomerId>1f323c97-2015-4a3d-9956-a93115c272ea</CustomerId>
        <FirstName>Aria</FirstName>
        <LastName>Stark</LastName>
        <DOB>1999-01-01T00:00:00</DOB>
    </Customer>
    <Customer>
        <CustomerId>c9c326c2-1e27-440b-9b25-c79b1d9c80ed</CustomerId>
        <FirstName>John</FirstName>
        <LastName>Snow</LastName>
        <DOB>1983-01-01T00:00:00</DOB>
    </Customer>
</ArrayOfCustomer>  

我的嘗試:

XElement toEdit = 
    (XElement)doc.Descendants("ArrayOfCustomer")
                 .Descendants("Customer")
                 .Where(x => Guid.Parse((x.Descendants("CustomerId") as XElement).Value) == customer.CustomerId)
                 .First<XElement>();

這會引發以下異常:

 Object reference not set to an instance of an object.

1) x不是XElement嗎?

2) 這是 lambda 用於選擇 Xml 節點的正確位置嗎?

3) 當然,您將如何根據CustomerId找到該節點?

您的問題是DescendentsWhere返回一個IEnumerable<XElement>而不是您所追求的單個XElement 您可以這樣解決:

XElement toEdit = doc.Descendants("ArrayOfCustomer")
                     .Descendants("Customer")
                     .Where(x => Guid.Parse(x.Descendants("CustomerId").Single().Value) == customer.CustomerId)
                     .FirstOrDefault();

你不是在投射x你在投射x.Descendants() x.Descendants() 返回一個集合,因此是復數方法語義。 在我的腦海中,你應該能夠做x.Descendants("CustomerId").FirstOrDefault() as XElement

XElement toEdit = (from c in doc.Descendants("Customer")
     where Guid.Parse(c.Value) == customer.CustomerId
     select c).SingleOrDefault();

我會像這樣重組您的查詢:

 XElement toEdit = doc.Descendants("Customer")
                      .Where(x => (Guid)x.Element("CustomerId") == customer.CustomerId)
                      .FirstOrDefault();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM