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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13342143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:15:27  来源:igfitidea点击:

XML parse check if attribute exist

c#xmllinqlinq-to-xml

提问by Joe

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?

我已经创建了一个方法来检查一个属性是否存在于 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";
        }
    }

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;

}

I made a XML-file with only one single row. The console prints out the value 15 times. Any ideas?

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

采纳答案by Joe

Solved! No extra method needed:

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

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

回答by Prabhu Murthy

You can try this and see if there is any improvement

你可以试试这个,看看是否有任何改进

class xmlAttributes
{
    public string Node;
    public Dictionary<string, string> Attributes;
} 

Now with this LINQ,all attributes are stored in a dictionary(per Node) and could be accessed through the attribute name.

现在有了这个 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)
                      });

Checks if an attribute exists on all XML Nodes

检查属性是否存在于所有 XML 节点上

var AttributeFound = Result.All(x => x.Attributes.ContainsKey("AttrName"));

Checks if the attribute appears at least once

检查属性是否至少出现一次

var AttributeFound = Result.Any(x => x.Attributes.ContainsKey("AttrName"));