I have two XELEMENTS XR and XTemp.
MY XR Contains :
<result xmlns="http://abc.com/test">
<report>
<unit unit_number="1" id="S1">
<classification>Subject</classification>
<claim_reported count="0" status="No claims reported" />
</unit>
<unit unit_number="2" id="S2">
<classification>Subject</classification>
<claim_reported count="0" status="No claims reported" />
</unit>
<unit unit_number="3" id="V1">
<classification>Vehicle</classification>
<claim_reported count="1" status="Claims reported" />
</unit>
......
</report>
</result>
My XTemp contains :
<result xmlns="http://abc.com/test">
<report>
<unit unit_number="1" id="S3">
<classification>Subject</classification>
<claim_reported count="1" status="Claims reported" />
</unit>
<unit unit_number="2" id="S4">
<classification>Subject</classification>
<claim_reported count="4" status="Claims reported" />
</unit>
<unit unit_number="3" id="V2">
<classification>Vehicle</classification>
<claim_reported count="0" status="No claims reported" />
</unit>
<unit unit_number="3" id="V3">
<classification>Vehicle</classification>
<claim_reported count="2" status="Claims reported" />
</unit>
......
</report>
</result>
Trying to extract all the <unit> elements from XTemp based on a certain condtion and add them to XR.
The condition is : get all the <unit> elements whose id begins with “V”.
Below code was the best I was able to come up with.
But, I get Object reference not set to an instance Error.
XR.Descendants(xmlns + "unit").LastOrDefault().AddAfterSelf(XTemp.Descendants(xmlns + "unit")
.Where(x => x.Element(xmlns + "unit").Attribute("id").Value.ToUpper().Contains("V")));
Thanks in advance
BB
Your problem is in this bit of code:
At that point in the query you’re already querying over
unitelements. Aunitdoesn’t contain a nestedunit, which is why you get aNullReferenceException.Change it to:
.Where(x => x.Attribute("id")...Personally, I find your query hard to read. Firstly,
LastOrDefaultmeans you potentially expect a null value to exist, yet you’re forging ahead with the rest of the query without addressing it. Secondly, you don’t need to find the lastunitelement andAddAfterSelf. Instead you can directlyAddto thereportelement and the elements will be appended to the end:Also, notice how I checked for “V” while ignoring the case. This is considered best practice as opposed to using
ToUpper.EDIT: based on the comments, here is a solution to sort all the
unitnodes while preserving the existing order of non-unitnodes. This code takes into account whether node occurs before and after existing nodes, or no other nodes at all.Some assumptions are:
unitnodesunitnodes are kept together and are not interspersed between all other types of nodes.The first two assumptions are trivial issues to code for if they’re incorrect.