XML解析检查属性是否存在 [英] XML parse check if attribute exist
本文介绍了XML解析检查属性是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经建立了一种检查XML文件中是否存在属性的方法.如果不存在,则返回"False".它可以工作,但是解析文件需要很长时间.似乎它读取每一行的整个文件.我在这里错过了什么吗?我可以通过某种方式使其更有效吗?
I've made a method which checks if an attribute exist in a XML-file. If it does not exist it returns "False". It works but it takes a very long time to parse the file. It seems it reads the whole file for each single row. Have I missed something here? Can I make it more effective somehow?
public static IEnumerable<RowData> 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";
}
}
我测试了用仅返回并接收字符串的方法替换该方法:
I tested to replace the method with one that only returns and receive string:
public static string checkXMLcount(string x)
{
Console.WriteLine(x);
Console.ReadLine();
return x;
}
我制作了一个只有一行的XML文件.控制台将输出该值15次.有什么想法吗?
I made a XML-file with only one single row. The console prints out the value 15 times. Any ideas?
推荐答案
已解决!无需其他方法:
Solved! No extra method needed:
countObject = spec.Attribute("mep_count") != null ? spec.Attribute("mep_count").Value : "False",
这篇关于XML解析检查属性是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文