I have a DataSet which has one table loaded with data.
When i write out the dataset to xml using the GetXml method of the dataset, i get all the columns in that data table as elements in the xml file.
How do i get the resulting xml with the column values as attributes instead of elements?
The article here trails off without a proper answer
I am using .NET Framework 2.0
Before writing the XML, do something like
foreach (DataColumn column in aDataSet.Tables[0].Columns)
{
column.ColumnMapping = MappingType.Attribute;
}
Although I'll admit I didn't test this. You still may get a DiffGram structured file.
foreach(DataColumn dc in dsHR.Tables[0].Columns)
dc.ColumnMapping = MappingType.Attribute;
Quite simple :)
Related
We have created a custom dataset and populating it with some data.
Before adding data, we are adding columns in the data set as follows
DataSet archiveDataset = new DataSet("Archive");
DataTable dsTable = archiveDataset.Tables.Add("Data");
dsTable.Columns.Add("Id", typeof(int));
dsTable.Columns.Add("Name", typeof(string));
dsTable.Columns.Add("LastOperationBy", typeof(int));
dsTable.Columns.Add("Time", typeof(DateTime))
Once the Dataset is create, we are filling values as follows
DataRow dataRow = dsTable.NewRow();
dataRow["Id"] = source.Id;
dataRow["Name"] = source.Name;
dataRow["LastOperationBy"] = source.LastOperationBy;
dataRow["Time"] = source.LaunchTime;
Is there any better and managed way of doing this. can I make the code more easy to write using enum or anything else to reduce the efforts?
You could try using a Typed Dataset.
This should get rid of the ["<column_name>"] ugliness.
If the dataset has a structure similar to tables in a database, then Visual Studio makes it really easy to create one: just click Add -> New Item somewhere in the solution and choose DataSet. VS will show a designer where you can drag tables from your server explorer.
Update (after response to Simon's comment):
A typed dataset is in fact an XSD (XML Schema Definition).
What I did in a similar case was:
created an empty DataSet (using Add -> New Item -> DataSet)
opened the newly created file with a text editor (by dafault, in VS it shows the XSD designer)
paste the XSD that I had created manually
You could also choose to use the designer to create the schema.
Considering your comment "I am using Dataset to export data to a XML file" I recommend using a different technology such as
Linq to XML http://msdn.microsoft.com/en-us/library/bb387061.aspx or
Xml Serialzation http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx
Or better yet of is doesnt have to be XML (and you only want hierarchical readable text consider JSON instead http://james.newtonking.com/pages/json-net.aspx
You can bind dataset in two way first one is using database second one is add manually.
After create column for dataset you can add using Loops you can add it if you have 10000 of entries.
You can use Reflection. Another option is to use EntityFramework or NHibernate to map the columnnames and datastructure columns and then avoid these code to fill each field manually. But they will add more complexity. Also Performance wise the your code is better.
I have two strings. One string is having XML Data and another string is having corresponding XML Schema. I am trying to read the data in DataTable. It looks like it is not possible. I don't want to use dataset. Is there a way I can combine the XML data and Schema into a memory stream and read?
Put simply, no, there is not a way to load xml directly into a DataTable through methods on DataTable nor is there a way to create a DataTable directly from an arbitrary schema. Such operations must be done through DataSet; otherwise, you end up doing some very involved workarounds.
There are some techniques you could apply using xml serialization that would be able to recreate a dataset from previously serialized xml. This does not allow for the use of an arbitrary schema though.
You could also write code specifically that loads your XML (via XDocument, XmlDocument, or XmlTextReader) and creates a DataTable on the fly, but it's not trivial to write and would likely take you quite some time. It's also kind of reinventing the wheel.
Essentially, the DataSet is the only class in that hierarchy with methods to process XML because Xml could contain any number of tables. To handle the broadest number of cases when you can make almost no assumptions about the XML, it has to be implemented at that level.
You could also consider whether it's appropriate to simply load the xml into an XDocument, validate it using the Validate extension method, and use Linq to Xml to query it.
Is there a way I can combine the XML data and Schema into a memory
stream and read?
Method
static DataTable ParseXML(string xmlString)
{
DataSet ds = new DataSet();
byte[] xmlBytes = Encoding.UTF8.GetBytes(xmlString);
Stream memory = new MemoryStream(xmlBytes);
ds.ReadXml(memory);
return ds.Tables[0];
}
Example:
string xml = new XElement("inventory",
new XElement("item",
new XElement("name", "rock"),
new XElement("price", "5000")),
new XElement("item",
new XElement("name", "new car"),
new XElement("price", "1"))).ToString();
DataTable dt = ParseXML(xml);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
Console.Write(row[col.ColumnName] + " | ");
Console.WriteLine();
}
I'd like to know what is the best practice.
I'm exporting some data (tables) from my database to XML files so I can read my data from them.
To export, I'm using DataTable.WriteXml (c#)
Now to read, what is best? to import them into a dataset and use DataTable.Select to get the row I want or create an XPathDocument and use XPath to get the data? which performs best? I'm still learning xpath.
Why not load the exported XML in using DataTable.ReadXml(fileName)? If you exported your table data using DataTable.WriteXml(file, XmlWriteMode.XmlSchema), then you can import it in to a new DataTable using ReadXml(file).
From an example in MSDN:
myOldTable.WriteXml(fileName, XmlWriteMode.WriteSchema);
DataTable newTable = new DataTable();
newTable.ReadXml(fileName);
If that's the case, I don't see where you'd need XPath. If I'm misunderstanding your question, please let me know and I'll update accordingly.
I hope this helps.
I've got in-memory dataset with couple of tables that is populated in code. Data-bound grids on the gui show table contents without a problem.
Then I try to export the dataset into XML:
ds.WriteXml(fdSave.FileName, XmlWriteMode.WriteSchema);
and get empty XML (with couple of lines regarding dataset names but without any tables)
If I export table directly I've got all the data but dataset name is obviously wrong:
ds.Fields.WriteXml(fdSave.FileName, XmlWriteMode.WriteSchema);
What am I missing? Is there any reasonable way to write the whole dataset into file?
ok, silly me. was clearing dataset tables collection before populating it...
Have a look at the documentation on DataSet.WriteXml:
http://msdn.microsoft.com/en-us/library/ms135425.aspx
and on XmlWriteMode:
http://msdn.microsoft.com/en-us/library/system.data.xmlwritemode.aspx
Try using XmlWriteMode.IgnoreSchema. The docs say for XmlWriteMode.WriteSchema "If the DataSet does not have a current schema, nothing is written."
you must add the data tables to your dataset like,
ds.Tables.Add(datatable1);
then write export it into the schema
I need a CSVParser class file
A Class File which parses csv and returns a dataSet as a result ASP.Net
I'm pretty sure that CSVReader (CodeProject) can read to DataTable.
DataTable table = new DataTable();
// set up schema... (Columns.Add)
using(TextReader text = File.OpenText(path))
using(CsvReader csv = new CsvReader(text, hasHeaders)) {
table.Load(csv);
}
Note that manually setting up the schema is optional; if you don't, I believe it assumes that everything is string.
Simple google gives plenty of results.
I've had luck with this parser. It will return results to a DataSet.
Another tool you might want to check out is FileHelpers. I see there's a tag for this resource here on SO.