As a general tip, I would say that I find it helpful to start these types of queries with the element that you are trying to extract data from i.e., instead of selecting the contract and working your way down, start with the FieldName element and use the .Parent property to filter your set of possibilities:
-
var fieldNames2 = (from f in xmlDoc.Descendants("FieldName")
-
where f.Parent.Name == "stuff"
-
and (int)f.Parent.Attribute("xID") == 32
-
//more predicate statements
-
select f.Attribute("name")).ToList()
-
-
The code can get quite complex depending on how many cases you have to take care of and how many levels up the XML document you have to go to do your filtering, but it should at least get you on the right track.
If you need more help, then please clarify your question. Your post says that dID may not exist, but your XML has the entire document element missing from the second Contract element. Do you have to account for the case where the Document element exists but does not have a dID attribute?
To cover all the bases, what would be the expected result set from the following example XML:
-
<Configuration>
-
<Contract xID="2">
-
<Document dID="227">
-
<FieldName name="AAAA"/>
-
<FieldName name="BBBB"/>
-
</Document>
-
</Contract>
-
<Contract xID="5">
-
<FieldName name="CCCC"/>
-
<FieldName name="DDDD"/>
-
</Contract>
-
<Contract xID="5">
-
<Document>
-
<FieldName name="EEEE"/>
-
<FieldName name="FFFF"/>
-
</Document>
-
</Contract>
-
<Contract xID="5">
-
<Document dID="227">
-
<FieldName name="GGGG"/>
-
<FieldName name="HHHH"/>
-
</Document>
-
</Contract>
-
<Contract xID="5" dID="227">
-
<FieldName name="IIII"/>
-
<FieldName name="JJJJ"/>
-
</Contract>
-
</Configuration>
-