I have the settings for my app in a simple XML document, like this:
<Settings>
<Server>
<Id>1</Id>
<Name>SRV123456</Name>
<Par Type="Desktop" Region="Western">12</Par>
<Par Type="Laptop" Region="Western">15</Par>
<Par Type="Desktop" Region="Eastern">22</Par>
<Par Type="Laptop" Region="Eastern">25</Par>
<State>WA</State>
</Server>
</Settings>
and am trying to query it using C# and LINQ, using this code:
xelement = XElement.Load(startpath + "\\Settings.xml");
var sn = from sl in xelement.Elements("Server")
where (string)sl.Element("State") == "WA"
where (string)sl.Element("Par").Attribute("Region") == "Western"
where (string)sl.Element("Par").Attribute("Type") == "Desktop"
select sl;
foreach (XElement xele in sn)
{
Console.WriteLine(xele);
Console.WriteLine(xele.Element("Par").Value);
}
This works for the first "Par" value, and will return "12". But if I change
where (string)sl.Element("Par").Attribute("Type") == "Desktop"
to
where (string)sl.Element("Par").Attribute("Type") == "Laptop"
It doesn't return any results... what am I missing?
Elementreturns the first element in document order. The attributes on that element will be the one's that are checked.Element(vsElements) and the order of the<Par>elements in the document. If<Par Type="Laptop" Region="Western">15</Par>was the first element named "Par" in the document, then the second line would work (and the first one wouldn't )