XML解析检查属性是否存在

时间:2012-11-12 10:34:17

标签: 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次值。有什么想法吗?

3 个答案:

答案 0 :(得分:39)

解决!无需额外的方法:

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

答案 1 :(得分:2)

您可以尝试这一点,看看是否有任何改进

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"));

答案 2 :(得分:0)

只想指出:

countObject = spec.Attribute("mep_count")?.Value;

哪条路一直向上:

countObject = spec?.Attribute("mep_count")?.Value

这将产生与countObject设置为null或值(如果存在)相同的效果。

相关问题