gpt4 book ai didi

c# - XML 解析检查属性是否存在

转载 作者:可可西里 更新时间:2023-11-01 03:12:54 25 4
gpt4 key购买 nike

我创建了一个方法来检查 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 次。有什么想法吗?

最佳答案

解决了!不需要额外的方法:

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

关于c# - XML 解析检查属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13342143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com