My requirement here is to retrieve the node that matches the hostname (for eg. machine1) and I always get back no results. Please let me know what the problem is?
Thanks for the help in advance!!!
XDocument configXML = XDocument.Load('the below xml'); var q = from s in configXML.Descendants('lcsetting') where ((string)s.Element('host') == hostName) select s;
The actual xml:
<lcsettings> <lcsetting env='prod'> <hosts usagelogpath=''> <host>machine1</host> <host>machine2</host> <host>machine3</host> </hosts> </lcsetting> <lcsetting env='qa'> <hosts usagelogpath=''> <host>machine4</host> <host>machine5</host> <host>machine6</host> </hosts> </lcsetting> <lcsetting env='test'> <hosts usagelogpath=''> <host>machine7</host> <host>machine8</host> <host>machine9</host> </hosts> </lcsetting> </lcsettings>
You’re looking for a
hostelement directly under an lcsetting – that doesn’t occur because there’s always ahostselement between the two in the hierarchy. You’re also usingElementinstead ofElements, which means only the first element with the right name will be returned.You could use
Descendantsagain instead ofElement… but you’ll need to change the condition. Something like:Alternatively, you could make your query find
hostelements and then take the grandparent element in each case:(This assumes a host element will only occur once per
lcsetting; if that’s not the case, you can add a call toDistinct.)