简体   繁体   中英

Quick way to get different node values from a file in C#?

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.

You can use anonymous type too:

var res = from xml in xDoc.Descendants("filePath")
          select new
          {
              Title = xml.Descendants("title").FirstOrDefault()?.Value,
              Label = xml.Descendants("label").FirstOrDefault(l => l.Ancestors("sec").Any())?.Value,
              Sec = xml.Descendants("sec").Attributes("id").FirstOrDefault()?.Value
          };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM