我编写了一个方法,用于检查XML文件中是否存在属性。如果它不存在,则返回"False“。它可以工作,但它需要很长的时间来解析文件。它似乎读取了每一行的整个文件。我是不是漏掉了什么?我能以某种方式让它更有效吗?
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";
}
}
我测试将该方法替换为只返回和接收字符串的方法:
public static string checkXMLcount(string x)
{
Console.WriteLine(x);
Console.ReadLine();
return x;
}
我创建了一个只有一行的XML文件。控制台将该值打印15次。有什么想法吗?
发布于 2012-11-13 20:22:18
解决了!不需要额外的方法:
countObject = spec.Attribute("mep_count") != null ? spec.Attribute("mep_count").Value : "False",
发布于 2012-11-12 19:18:44
你可以试试这个,看看有没有什么改进
class xmlAttributes
{
public string Node;
public Dictionary<string, string> 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"));
发布于 2020-06-24 11:12:32
我只想指出:
countObject = spec.Attribute("mep_count")?.Value;
它在整个链条上都起作用:
countObject = spec?.Attribute("mep_count")?.Value
这将产生相同的效果,其中countObject将被设置为null或该值(如果存在)。
https://stackoverflow.com/questions/13342143
复制相似问题