Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write this xml in c#

Tags:

c#

xml

What's the best way to produce this xml programmatically and persist to file? The data source is just going to be a csv file (you may suggest the csv file be formed another way if it makes programming the xml easier (flexible in this area)):

business name, address line
Comapny Name 1, 123 Main St.
Company Name 2, 1 Elm St.
Company Name 2, 2 Eml St.

<?xml version="1.0"?> 
<ArrayOfBusiness xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
  <Business> 
    <Name>Company Name 1</Name> 
    <AddressList> 
      <Address> 
        <AddressLine>123 Main St.</AddressLine> 
      </Address> 
    </AddressList> 
  </Business> 
  <Business> 
    <Name>Company Name 2</Name> 
    <AddressList> 
      <Address> 
        <AddressLine>1 Elm St.</AddressLine> 
      </Address> 
      <Address> 
        <AddressLine>2 Elm St.</AddressLine> 
      </Address> 
    </AddressList> 
  </Business> 
</ArrayOfBusiness> 
like image 347
Rod Avatar asked Feb 25 '26 07:02

Rod


1 Answers

string path = @"C:\Path\To\Output.xml";
List<Business> list = // set data 

using (var streamWriter = new StreamWriter(new FileStream(path, FileMode.Write)))
{
  using (var xmlWriter writer = new XmlTextWriter(streamWriter))
  {
    var serialiser = new XmlSerializer(typeof(List<Business>));
    serialiser.Serialize(xmlWriter, list);
  }
}
like image 167
Matthew Abbott Avatar answered Feb 27 '26 20:02

Matthew Abbott