2013-04-30 271 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

相关问题