Finding a specific XML element based on an ID using Linq -
I want to search for a section of XML based on criteria so that I am using XML in XML. Unfortunately the result is always nullified, so I think I have done something wrong. The example of the XML shown below is I am parsing.
& lt; Content & gt; & Lt; ItemsA / & gt; & Lt; ITEMB / & gt; & Lt; ItemsC> & Lt; Item xmlns: i = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://schemas.datacontract.org/2004/07/Stuff" & gt; & Lt; Eid & gt; 4bd7b5ac-cb29-4d34-97be-deaebe4a5186 & lt; / Id & gt; & Lt; Children & gt; & Lt; Item & gt; & Lt; Id & gt; 22e3ef6b-4321-40c3-9237-196ba527e9ad & lt; / Id & gt; & Lt; Name & gt; SomeName & lt; / Name & gt; & Lt; / Item & gt; & Lt; / Children & gt; & Lt; Details & gt; SomeText & lt; / Details & gt; & Lt; Name & gt; NewName & lt; / Name & gt; & Lt; / Item & gt;
I am looking at the "Items C" section where XML can have many "item" blocks (only one shown in this example). I want to retrieve the element based on its "id", which has an ID of "4bd7b5ac-cb29-4d34-97be-deaebe4a5186" in the above example.
The code I used is shown below:
XElement data = XElement.Parse (GetFile ());
var pbp = (Data is residual ("item") in B. Where b.Element ("id"). Value == "4bd7b5ac-cb29-4d34-97be-deaebe4a5186" Select b.Element ("Id"). Parents FirstOffer Default ();
pbp always returns zero as to help me produce the correct linq expression
Yes - you're missing only the namespace:
string is the desired id = "4bd7b5ac-cb29-4d34-97be-deaebe4a5186"; XNamespace ns = "http://schemas.datacontract.org/2004/07/Stuff"; Var pbp = Out of. Residual (ns + "item") where b.Element (ns + "Id"). Value == Select the desired id b) FirstOrDefault ();
Note that I have simplified the b.Element ("Id"). Parents
just b
- If you're just going down the tree and again again, where you Also be there to be there :)
It suggests simplification to use dot notation and:
If there is an opportunity that element will not have the "id" element, then you can put it in a string instead:
string desiredId = " 4bd7b5ac-cb29-4d34-97be-deaebe4a5186 "; XNamespace ns = "http://schemas.datacontract.org/2004/07/Stuff"; Var pbp = data.Descendants (ns + "items"). Where (b = & gt; (string) B. element (ns + "id") == desired id). FirstOver Default ();
This saves the potential nullification exception.
Comments
Post a Comment