How to create an XML tree with attributes using LINQ

Asked

Viewed 258 times

0

Good night! 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>

1 answer

1

I didn’t really understand your question because there is no way to use a general xml... For access to data from a certain collection, in the example below we use Xelement and Xattribute to help us with this.

But I believe that link Creating XML Trees in C# (LINQ to XML) will be usual.

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.