Linq to XML: Finding value of a specific element
I am new bee to "Linq" and "Linq to XML" concepts. I have the following xml tree
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>IWS</name>
<SSIDConfig>
<SSID>
<hex>496153</hex>
<name>ISL</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>networkKey</keyType>
<protected>false</protected>
<keyMaterial>BFEBBEA9B0E78ECD671A8D35D96556A32E001B7524A1</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>
I was wondering how to retrieve the KeyMaterial element value using linq to xml?
I have tried to use the following code, but I get empty e开发者_如何转开发numeration
var networkKey = from c in doc.Descendants("WLANProfile")
select (string)c.Element("keyMaterial").Value;
Any suggestions?
Two mistakes:
1.) keyMaterial
is not a direct child of WLANProfile
that's why you don't get any results (c.Elements will only look for a direct child)
2.) you need to use the specified namespace in the XML - otherwise no node will match
Both applied:
XNamespace xns = "http://www.microsoft.com/networking/WLAN/profile/v1";
var networkKey = (from c in doc.Descendants(xns + "keyMaterial")
select (string)c.Value).FirstOrDefault();
Somewhat shorter in dot notation if you know there is always going to be exactly one key:
string networkKey = xdoc.Descendants(xns + "keyMaterial").Single().Value;
精彩评论