XML解析检查属性是否存在

Joe*_*Joe 15 c# xml linq linq-to-xml

我已经创建了一个方法来检查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";
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*Joe 40

解决了!无需额外的方法:

countObject = spec.Attribute("mep_count") != null ? spec.Attribute("mep_count").Value : "False",
Run Code Online (Sandbox Code Playgroud)

  • 如果你有很多这些...你可以封装.......私有字符串SafeAttributeValue(XAttribute xattr){string returnValue = string.Empty; if(null!= xattr){returnValue =(string)xattr.Value; } return returnValue; } (2认同)