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

标签 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";
        }
    }

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

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/

相关文章:

c# - 使用哪个 linq 在当前集合中的集合中进行集合搜索

python - 在python中解析大型伪xml文件

ruby - 在 Ruby 中读取 XML 注释值

c# - 反转字典中的键和值

c# - 使用 LINQ 将 CLR 对象写入 XML

c# - ASP.NET MVC3 路由 - 不同区域的相同 URL

c# - 如何在 EF 和 C# 中编写用于检索 IEnumerable 对象的类

c# - 在 .Net 后端 Azure 移动服务中使用 Microsoft 帐户对用户进行身份验证,登录后出现错误

python - 使用 lxml 生成 XHTML 文档的推荐方法

c# - 对于带索引的嵌套选择,ImmutableArray<> 的行为不同于 Array<>