views:

1098

answers:

3

In C#, I'm creating an XML file from a DataTable using dataTable.WriteXml(filePath), and get the following:

<?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
  <ExperienceProfile>
    <Col1>blah</Col1>
    <Col2>4ed397bf-a4d5-4ace-9d44-8c1a5cdb0f34</Col2>
  </ExperienceProfile>
</ExperienceProfiles>

How can I get it to write the XML in the following format?:

<?xml version="1.0" encoding="utf-8" ?>
<ExperienceProfiles>
  <ExperienceProfile Col1="blah"
    Col2="blah" ></ExperienceProfile>
</ExperienceProfiles>
A: 

Short answer: you can't, using the WriteXml method of a DataTable.

Long answer (which is not very long): Just roll your own.

Retract my answer, as per above :)

Strelok
+4  A: 

What you want is some way to tell the DataSet the expected format of your data. You're in luck, the DataSet supports just this feature.

You will need to create an XML schema for your data and load it into the DataSet before you write out the XML. In the schema define Col1 and Col2 as attributes of the ExperienceProfile element and the DataSet will know to format the output document to meet the requirements specified in the schema.

If you are not comfortable with creating a schema you can create a sample of the XML file the way that you want it to be formatted, then take a look at the XmlSchemaInference class in the framework. This class can be used to automatically generate your schema, you may need to tweak the output a little but it can help if you are not familiar with XSD.

joshperry
To make it even better, open the sample XML document in VIsual Studio, and select "Generate Schema" from the XML Menu!
Mitchel Sellers
Thanks. I'm definitely familiar with schema's -- I was hoping there would be a parameter that I overlooked on WriteXml that would make it that much simpler.
Whytespot
+3  A: 

you can use the ColumnMapping feature of the datatable column. .

column.ColumnMapping = MappingType.Attribute
Just what I needed; thanks!
JohnB