2012-11-12 20 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"; 
     } 
    } 

私は1つだけが戻って方法を交換し、文字列を受け取るためにテスト:

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

} 

私はただ1つの行を持つXMLファイルを作りました。コンソールは値を15回印刷します。何か案は?あなたはこれを試してみて、どんな改善

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

は、このLINQで今そこにあるかどうかを確認することができます

+0

XPathの独自のバージョンを作成するのはなぜですか? – raina77ow

答えて

37

解決!特別な方法は必要ありません。

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

これらの多くをお持ちの場合...カプセル化することができます....... private string SafeAttributeValue(XAttribute xattr) { string returnValue = string.Empty; if(null!= xattr) { returnValue =(文字列)xattr.Value; } return returnValue; } – granadaCoder

2

、すべての属性が(ノードあたり)ディクショナリに格納され、属性名を介してアクセスすることができます。

すべてのXMLノード

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

小切手上の

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

チェックした属性が存在する場合、属性が少なくとも一度表示された場合

var AttributeFound = Result.Any(x => x.Attributes.ContainsKey("AttrName")); 
関連する問題