2010-02-16 13 views
2

缺少的元素,我有以下XMLXLINQ:在XML

<students> 
    <student> 
    <id>12</id> 
    <name>Mohsan</name> 
    </student> 
    <student> 
    <id>2</id>  
    </student> 
    <student> 
    <id>3</id> 
    <name>Azhar</name> 
    </student> 
</students> 

請注意,在2名元素缺失。

我要讀使用LINQ to XML

我用下面的代碼來獲取所有學生這個XML ..

請建議我提高這個代碼

var stds = from std in doc.Descendants("student") 
       select new 
       { 
        ID = std.Element("id").Value, 
        Name = (std.Element("name")!=null)?std.Element("name").Value:string.Empty 
       }; 

回答

6

您可以使用事實上有一個explicit conversion from XElement to string,它返回空的XElement參考。然後,您可以使用空合併運算符從空轉到一個空字符串:

var stds = from std in doc.Descendants("student") 
      select new 
      { 
       ID = std.Element("id").Value, 
       Name = (string) std.Element("name") ?? ""; 
      }; 
+0

hmmmm。不錯的選擇 – Mohsan 2010-02-16 12:47:30

5

語法與「讓'允許您避免兩次詢問元素(「名稱」)

var stds = from std in doc.Descendants("student") 
      let elName = std.Element("name") 
      select new 
      { 
       ID = std.Element("id").Value, 
       Name = (elName!=null)?elName.Value:string.Empty 
      }; 
+0

我可以使用?爲了這。它給我錯誤。 Name = std.Element(「name」)?? string.Empty – Mohsan 2010-02-16 12:33:28

+0

@Mohsan std.Element(「name」)?? ?? - 解析XML元素,而不是字符串,另一方面string.Empty是一個字符串,所以它是類型不兼容的。不幸的是std.Element(「name」)。ToString()?也會因爲NullPointerException而失敗。 – Dewfy 2010-02-16 13:45:20

1

這是晚了一點,但可以幫助別人通過這個期待。我有一個相當大的對象,它有90個屬性,我試圖從XML文件中投入,所以爲了使事情更輕鬆,我創建了一些方法。

private static object CheckElement(XElement element) 
    { 
     return string.IsNullOrEmpty((string)element) ? null : element.Value; 
    } 

    public static string CheckElementString(XElement element) 
    { 
     return (string)CheckElement(element); 
    } 

    public static Int16 CheckElementInt(XElement element) 
    { 
     var theResult = CheckElement(element); 

     return theResult == null ? (short)-1 : Convert.ToInt16(theResult); 
    } 

    public static DateTime? CheckElementDateTimeNullable(XElement element) 
    { 
     var theResult = CheckElement(element); 

     return theResult == null ? (DateTime?)null : DateTime.Parse(theResult.ToString()); 
    } 

    public static decimal CheckElementDecimal(XElement element) 
    { 
     var theResult = CheckElement(element); 

     return theResult == null ? 0.00M : Convert.ToDecimal(theResult); 
    } 

    public static bool CheckElementBoolean(XElement element, bool defaultValue) 
    { 
     var theResult = CheckElement(element); 

     return theResult == null ? defaultValue : Convert.ToBoolean(theResult); 
    } 

然後,它是很容易使用這樣的:

var stds = from std in doc.Descendants("student") 
     select new 
     { 
      ID = std.Element("id").Value, 
      Name = CheckElementString(std.Element("name")) 
     };