2010-12-02 16 views
10
<books> 
    <book name="Christmas Cheer" price="10" /> 
    <book name="Holiday Season" price="12" /> 
    <book name="Eggnog Fun" price="5" special="Half Off" /> 
</books> 

私はlinqを使ってこれを解析したいと思っています。私の現在の作業方法は次のとおりです。Linq To Xml Null属性のチェック

var books = from book in booksXml.Descendants("book") 
         let Name = book.Attribute("name") ?? new XAttribute("name", string.Empty) 
         let Price = book.Attribute("price") ?? new XAttribute("price", 0) 
         let Special = book.Attribute("special") ?? new XAttribute("special", string.Empty) 
         select new 
            { 
             Name = Name.Value, 
             Price = Convert.ToInt32(Price.Value), 
             Special = Special.Value 
            }; 

これを解決する方法があるかどうかは疑問です。 Tがタイプである場合にのみ動作すること

public static class XmlExtensions 
{ 
    public static T AttributeValueOrDefault<T>(this XElement element, string attributeName, T defaultValue) 
    { 
     var attribute = element.Attribute(attributeName); 
     if (attribute != null && attribute.Value != null) 
     { 
      return (T)Convert.ChangeType(attribute.Value, typeof(T)); 
     } 

     return defaultValue; 
    } 
} 

注:欠落している属性の例をカプセル化するために拡張メソッドを使用する方法について

おかげで、

  • ジャレッド

答えて

11

属性をstringにキャストできます。存在しない場合は、nullを取得し、その後のコードでnullをチェックする必要があります。それ以外の場合は、値を直接返します。

代わりにこれを試してみてください:C#の6.0では

var books = from book in booksXml.Descendants("book") 
      select new 
      { 
       Name = (string)book.Attribute("name"), 
       Price = (string)book.Attribute("price"), 
       Special = (string)book.Attribute("special") 
      }; 
+0

それは素晴らしいです!大好きです。ありがとう。 – Howel

4

方法文字列はIConvertible経由で変換することを知っています。より一般的な変換のケースをサポートしたい場合は、TypeConverterを探す必要があります。タイプが変換に失敗した場合、これは例外をスローします。これらのケースでもデフォルトを戻すには、追加のエラー処理を行う必要があります。

+0

私はこのバリアントを使用しましたが、 'XAttribute Attribute (このXElement要素、XName名、T defaultValue)'を使用しました。それが失敗した場合は、新しいXAttribute(name、defaultValue);を作成します。その後、元のものと一緒に過負荷があります –

0

はあなたの例では、それを適用した後モナドヌル条件演算子?. を使用することができ、それは次のようになります。

var books = from book in booksXml.Descendants("book") 
      select new 
      { 
       Name = book.Attribute("name")?.Value ?? String.Empty, 
       Price = Convert.ToInt32(book.Attribute("price")?.Value ?? "0"), 
       Special = book.Attribute("special")?.Value ?? String.Empty 
      }; 

あなたが読むことができますhereの部分は、Null-conditional演算子です。