2012-04-10 18 views
6

mój plik XML:Wybierz węzeł XML przy użyciu LINQ do 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> 

moja próba:

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

to rzuca następujący wyjątek:

Object reference not set to an instance of an object. 

1) nie jest xXElement?

2) czy jest to właściwe, gdzie lambda do wyboru węzła Xml?

3) i oczywiście w jaki sposób można znaleźć ten węzeł zgodnie z CustomerId?

+0

raz pierwszy dostał wyjątek: Nie można rzutować obiektu typu „WhereEnumerableIterator'1 [System .Xml.Linq.XElement] ", aby wpisać" System.Xml.Linq.XElement ". było tak, ponieważ próbowałem odrzucić z IEumumble do pojedynczego XElement, dodałem do niego rozszerzenie First (). teraz po prostu nie może odczytać x jako XElement. –

Odpowiedz

4

Twój problem polega na tym Descendents i Where zwrócić nie IEnumerable<XElement> pojedynczy XElement co jest, co jesteś po. Można rozwiązać ten problem tak:

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

Należy pamiętać, że pod klientem musi znajdować się tylko jeden element CustomerId. Jeśli jest 0 lub> 1, rzuci wyjątek. A po obejrzeniu jego XML prawdopodobnie jest to odpowiednie. Ale po prostu coś do wskazania. –

+0

@AndrewFinnell, gdy były na temat, jak byś zmienił ten węzeł, mogę teraz zaktualizować wszystkich klientów decententów klienta (XElement) , ale jak zaktualizować węzeł w pliku? –

2

Nie odlewasz x odlewasz x.Descendants(). x.Descendants() zwraca kolekcję, stąd też metoda semantyczna w liczbie mnogiej. Poza czubek głowy powinien być w stanie zrobić x.Descendants("CustomerId").FirstOrDefault() as XElement

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

chciałbym zrestrukturyzować zapytanie tak:

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