I have products in a class that I want to save in a XML file, the products is devided into categoris and I would like to save my products in a XML file formatet like below examlple. Products for category 1 writes under category one and products for category 2 under category two.
Hwo can I write a method that dose that?
Thanks in advance.
<Categories>
<Category ID="1">
<CategoryName>Categoriname1</CategoryName>
<Description>drinks, coffees, beers, ales</Description>
<Products>
<Product>
<ProductName>Coffe</ProductName>
<QuantityPerUnit>15 boxes x 60 bags</QuantityPerUnit>
<UnitPrice>25</UnitPrice>
<UnitsInStock>3</UnitsInStock>
<UnitsOnOrder>0</UnitsOnOrder>
</Product>
<Product>
<ProductName>Chang</ProductName>
<QuantityPerUnit>24 - 12 oz bottles</QuantityPerUnit>
<UnitPrice>19</UnitPrice>
<UnitsInStock>17</UnitsInStock>
<UnitsOnOrder>40</UnitsOnOrder>
</Product>
</Products>
</Category>
<Category ID="2">
<CategoryName>Condiments</CategoryName>
<Description>spreads, and seasonings</Description>
<Products>
<Product>
<ProductName>Productname</ProductName>
One option is to use LINQ to XML. Assume you have these classes (where I have removed some properties to simplify the example):
You can create some test data:
You can then create an
XDocumentfrom the test data:To save it to a file you can use the
Savemethod: