2012-11-12 92 views
12

我做了一個方法來檢查屬性是否存在於XML文件中。如果它不存在,則返回「False」。它可以工作,但解析文件需要很長時間。它似乎讀取每一行的整個文件。我在這裏錯過了什麼嗎?我能否以某種方式使它更有效?XML解析檢查屬性是否存在

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次。有任何想法嗎?

+0

爲什麼編寫自己的XPath版本,我想知道? – raina77ow

回答

37

解決了!不需要額外的方法:

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

如果你有很多這些......你可以封裝.......私人字符串SafeAttributeValue(XAttribute xattr) { string returnValue = string.Empty;如果(空!= xattr) { returnValue =(string)xattr.Value; } return returnValue; } – granadaCoder

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