Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create xml from a template-c#

Tags:

c#

.net

xml

I have a xml template like this

<User>
<UserId></UserId>
<UserName></UserName>
<Roles>
<Role></Role>
<Roles></Role>
</Roles>
</User>

Form this xml template file,dynamicaly i want to generate an xml.How can i do this.

Output xml should look like this

<User>
<UserId>user1</UserId>
<UserName>fr</UserName>
<Roles>
<Role>abc</Role>
<Role>def</Role>
</Roles>
</User>

How can i achieve this.What all changes i need to make in template file.How to read and create xml from this tempalte xml file using c#.

like image 453
user922834 Avatar asked Dec 20 '22 23:12

user922834


1 Answers

You can use XmlSerializer and create a simple class with properties according to the template:

public class User
{
   public UserId{get;set;}

   ...
}

And serialize the class to XML file.

There's a good example here.

Option #2:
If for some reason you do not want to use XmlSerializer use XmlWriter - in order to prevent forgetting to close elements I suggest you use "AutoClose" XmlWriter - I've blogged about how to create this simple class on my blog - XmlWriter that automatically close elements using IDisposable

like image 51
Dror Helper Avatar answered Dec 23 '22 14:12

Dror Helper