XML解析检查属性是否存在

我已经创建了一个方法来检查XML文件中是否存在属性。 如果它不存在则返回“False”。 它可以工作,但解析文件需要很长时间。 它似乎读取每一行的整个文件。 我错过了什么吗? 我能以某种方式使它更有效吗?

public static IEnumerable getXML(string XMLpath) { XDocument xmlDoc = XDocument.Load("spec.xml"); var specs = from spec in xmlDoc.Descendants("spec") select new RowData { number= (string)spec.Attribute("nbr"), name= (string)spec.Attribute("name").Value, code = (string)spec.Attribute("code").Value, descr = (string)spec.Attribute("descr").Value, countObject = checkXMLcount(spec), return specs; } public static string checkXMLcount(XElement x) { Console.WriteLine(x.Attribute("nbr").Value); Console.ReadLine(); try { if (x.Attribute("mep_count").Value == null) { return "False"; } else { return x.Attribute("mep_count").Value; } } catch { return "False"; } } 

我测试用一个只返回和接收字符串的方法替换方法:

 public static string checkXMLcount(string x) { Console.WriteLine(x); Console.ReadLine(); return x; } 

我制作了一个只有一行的XML文件。 控制台打印出15次值。 有任何想法吗?

解决了! 无需额外方法:

 countObject = spec.Attribute("mep_count") != null ? spec.Attribute("mep_count").Value : "False", 

您可以尝试这个,看看是否有任何改进

 class xmlAttributes { public string Node; public Dictionary Attributes; } 

现在使用此LINQ,所有属性都存储在字典中(每个节点),并且可以通过属性名称进行访问。

 var Result = XElement.Load("somedata.xml").Descendants("spec") .Select(x => new xmlAttributes { Node = x.Name.LocalName, Attributes = x.Attributes() .ToDictionary(i => i.Name.LocalName, j => j.Value) }); 

检查所有XML节点上是否存在属性

 var AttributeFound = Result.All(x => x.Attributes.ContainsKey("AttrName")); 

检查属性是否至少出现一次

 var AttributeFound = Result.Any(x => x.Attributes.ContainsKey("AttrName"));