2013-06-12 53 views
0

我建立這個XML文件:XML有條件的XElement創建

var persons = new[] { 
    new Person { 
     Name = "Patrick Hines", 
     PhoneNumbers = new[] { "206-555-0144", "425-555-0145" } 
    }, 
    new Person { 
     Name = "Gretchen Rivas", 
     PhoneNumbers = new[] { "206-555-0163" } 
    } 
}; 
      XElement contacts = 
       new XElement("contacts", 
        from p in persons 
        where p.Name.StartsWith("G") 
        select new XElement("contact", 
        new XElement("name", p.Name), 
        from ph in p.PhoneNumbers 
        select new XElement("phone", ph) 
       ) 
       ); 


     class Person 
     { 
      public string Name; 
      public string[] PhoneNumbers; 
     } 

在此示例中PHONENUMBER不爲空。我該如何編碼它不會在電話號碼字符串爲空或空的時候在我的xml中創建一個元素?從PHONENUMBERS

+0

添加'where'表達。例如。 '從p.PhoneNumbers中的ph開始,其中ph!= null 選擇新的XElement(「phone」,ph)' – adatapost

回答

0

篩選出空和空字符串:

from ph in p.PhoneNumbers where !String.IsNullOrEmpty(ph)