How to create an XML tree with attributes using LINQ

0

Good evening! How do I create an XML document with attributes using LINQ to XML

EX:

<class name="Pessoa" tabela="pessoa">
    <property name="id" column="id" pk="true"/>
    <property name="nome" column="nome"/>
    <property name="genero" column="genero"/>
    <property name="dataNasc" column="data_nasc" type="date"/>
</class>
    
asked by anonymous 13.09.2014 / 03:31

1 answer

1

I do not understand your question very much as there is no way to use linq for a general xml ... linq and for data access for a particular collection, in the example below we use XElement and XAttribute to help us with this.

But I believe this Creating XML Trees in C # (LINQ to XML) will be customary .

To create attributes use XAttribute, XElement elements.

var obj = new[]
{    
 new {ID = 1, Nome= "A", Fone = "999999999"},    
 new {ID = 2, Nome= "B", Fone = "125125125},    
 new {ID = 3, Nome= "C", Fone = "346346345"},    
 new {ID = 4, Nome= "D", Fone = "568658568"}  

};

XElement _cliente= new XElement("customers",
                    from c in obj
                    orderby c.ID //descending 
                    select new XElement("customer",
                        new XElement("name", c.Nome),
                        new XAttribute("ID", c.ID),
                        new XElement("telefone", c.Fone)
                                        )
                                );

Console.WriteLine(_cliente);
    
14.09.2014 / 00:30