Alasse
Alasse

Reputation: 361

Writing into xml with more than one lines

I am developing a c# application. I need to write company-product details in this form. One company may have more than one product and one xml file may contain only 1 company. So one xml file for every company.

<?xml version="1.0" encoding="utf-8" ?>
<list>
  <CompanyName>Test</CompanyName>
  <CompanyID>TestID</CompanyID>
  <Product>
    <ProductName>Prod</ProductName>
    <ProductID>ProdID</ProductID>
    <Expire>10.10.2010</Expire>
  </Product>
  <Product>
    <ProductName>Prod2</ProductName>
    <ProductID>ProdID2</ProductID>
    <Expire>11.10.2010</Expire>
  </Product>
  <Product>
    <ProductName>Prod3</ProductName>
    <ProductID>ProdID3</ProductID>
    <Expire>12.10.2010</Expire>
  </Product>
</list>

How can i make one xml file to have 3 attributes in c#?

I would appreciate your helps.

Regards

Upvotes: 2

Views: 236

Answers (1)

Irfan
Irfan

Reputation: 2771

If you are asking how to write an xml file in C# then you have write a class provide xml attributes to class and its properties, and then serialize the class.

Instance of the class with all its data will be serialized to xml:

Here is an example in your situation.

[XmlType(TypeName = "CompanyXml")]
public class Company : ISerializable
{
    [XmlElement("Product")]
    public List<Product> ListProduct { get; set; }

    [XmlElement("CompanyName")]
    public string CompanyName { get; set; }

    [XmlElement("CompanyID")]
    public string CompanyID { get; set; }
}

Product class looks like:

[XmlType(TypeName = "Product")]
public class Product : ISerializable
{
    [XmlElement("ProductName")]
    public string ProductName { get; set; }

    [XmlElement("ProductID")]
    public string ProductID { get; set; }

    [XmlElement("Expires")]
    public string Expires { get; set; }
}

Serialization code could follow as:

using (StringWriter stringWriter = new StringWriter())
{
  XmlSerializer serializer = new XmlSerializer(typeof(Company));
  serializer.Serialize(stringWriter, companyInstance);
  XmlDocument xDoc = new XmlDocument();
  xDoc.LoadXml(stringWriter.ToString());
 }

Upvotes: 2

Related Questions