2013-04-30 256 views
4

我試圖從列表創建XML。我從列表中創建一個匿名類來生成XML:如果值不爲空,則創建XElement

var xEle = new XElement("Employees", 
       from emp in empList 
       select new XElement("Employee", 
          new XElement("ID", emp.ID), 
           new XElement("FName", emp.FName), 
          new XElement("LName", emp.LName) 
        )); 

如何處理,如果FnameLname爲空?

另外我想要動態添加元素只有當對象不爲空。例如,如果Fname是空的,我需要跳過創建FNAME:

new XElement("ID", emp.ID), 
new XElement("LName", emp.LName) 

我該怎麼辦呢?

+3

您還沒有表現出任何匿名類。 – 2013-04-30 07:31:40

+0

'xEle'只是一個查詢,因爲它站着 – DGibbs 2013-04-30 07:35:25

+0

更改標題.. – user2067567 2013-04-30 07:38:38

回答

11

您的代碼實際上並不顯示匿名類型 - 僅創建了XElement。但是,您可以使用LINQ to XML將在添加內容時忽略null值的事實。所以,你可以使用:

select new XElement("Employee", 
        new XElement("ID", emp.ID), 
        emp.FName == null ? null : new XElement("FName", emp.FName), 
        emp.LName == null ? null : new XElement("LName", emp.LName) 
        ) 

或者你可以在string編寫擴展方法:

public static XElement ToXElement(this string content, XName name) 
{ 
    return content == null ? null : new XElement(name, content); 
} 

裏調用:

select new XElement("Employee", 
        emp.ID.ToXElement("ID"), 
        emp.FName.ToXElement("FName"), 
        emp.LName.ToXElement("LName")) 
+0

AWSOME ... :)謝謝@jon – user2067567 2013-04-30 07:43:00

+0

優秀的解決方案,我的問題,謝謝喬恩! – delliottg 2013-08-16 21:05:09

+0

沒有回到我原來的評論,很快就添加了這個:對於我如何使用這個,請看我的SO問題在這裏的例子:[添加列到數據集被用作XML父節點](http: //www.stackoverflow.com/questions/18220709/add-columns-to-dataset-to-be-used-as-xml-parent-nodes) – delliottg 2013-08-16 21:16:23

相關問題