I want to get the values of different nodes using different conditions of a xml file in different variables. Below is an example
XDocument doc = XDocument.Load(@"D:\MyFiles\test.xml", LoadOptions.PreserveWhitespace);
var a = (from x in doc.Descendants("title")
select x).First().Value;
var b = (from y in doc.Descendants("label")
where y.Ancestors("sec").Any()
select y).First().Value;
var c = (from z in doc.Descendants("sec").Attributes("id")
select z).First().Value;
Can I do this in one line of code or maybe in a less redundant way?
Well you certainly don't need to use the query expressions - they're mostly just getting in the way. This code would be simpler as:
XDocument doc = XDocument.Load(@"D:\MyFiles\test.xml",LoadOptions.PreserveWhitespace);
var a = doc.Descendants("title").First().Value;
var b = doc.Descendants("label").First(y => y.Ancestors("sec").Any()).Value;
var c = doc.Descendants("sec").Attributes("id").First().Value;
Alternatively, you could use XPath if you wanted. (XPathSelectElements
, XPathEvaluateNode
etc.) Personally I prefer to keep to using the query methods provided by LINQ to XML though.
See more on this question at Stackoverflow