简体   繁体   English

从C#文件中获取不同节点值的快速方法?

[英]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. 我想使用不同变量的xml文件的不同条件来获取不同节点的值。 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. 或者,您可以根据需要使用XPath。 ( XPathSelectElements , XPathEvaluateNode etc.) Personally I prefer to keep to using the query methods provided by LINQ to XML though. XPathSelectElementsXPathEvaluateNode等。)我个人还是比较喜欢使用LINQ to XML提供的查询方法。

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
          };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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