C# DataSet To Xml, Node Rename - c#

DataSet ds = GetExcelToXml("test.xls");
string filename = #"C:\test.xml";
FileStream myFileStream = new FileStream(filename, FileMode.Create);
XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Default);
ds.WriteXml(myXmlWriter);
myXmlWriter.Close();
Output Xml
<NewDataSet>
<Table>
<UserName>bla1</User_Name>
<Mail>bla1#bla2.com</Mail>
<Address>World</Address>
</Table>
</NewDataSet>
I need Xml Node Name
<ROWS>
<ROW>
<UserName>bla1</User_Name>
<Mail>bla1#bla2.com</Mail>
<Address>World</Address>
</ROW>
</ROWS>
How To Make ?

Try this,
ds.DataSetName = "ROWS";
ds.Tables[0].TableName = "ROW";
ds.WriteXml(myXmlWriter);
myXmlWriter.Close();

XmlDocument myXml;
myXml.Load(myXmlWriter); //Not sure if this will work, but you get the idea
myXml.InnerXml = myXml.InnerXml.Replace("< NewDataSet", "< ROWS")
.Replace("< /NewDataSet>", "< /ROWS>")
.Replace("< Table", "< ROW")
.Replace("< /Table>", "< /ROW>");

Here is a sample C# application which will read the input XML and then copy different XML/Data tables to other files using the Table name:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataSet dsXml = new DataSet();
dsXml.ReadXml("mydata.xml");
for (int i = 0; i < dsXml.Tables.Count; i++)
{
Console.WriteLine("Table Name: " + dsXml.Tables[i].TableName);
DataSet newDataSet = new DataSet();
newDataSet.Tables.Add(dsXml.Tables[i].Copy());
FileStream myFileStream = new FileStream(dsXml.Tables[i].TableName + ".xml", FileMode.Create);
XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, Encoding.Default);
newDataSet.WriteXml(myXmlWriter);
myXmlWriter.Close();
}
}
}
}

In case anyone comes here looking for the opposite direction problem where a typed dataset table name has changed since the xml files were written.
// for xml files created prior to rename of Sample table to SampleS,
// rename the Sample table, read xml,
// then rename table back to current SampleS
if (ds.SampleS.Count == 0)
{
ds = new AnalysisDSX();
ds.Tables["SampleS"].TableName = "Sample";
ds.ReadXml(xmlFilePath);
ds.Tables["Sample"].TableName = "SampleS";
}

Related

Query on XML parsing in C#?

But it gives me exception like "There are multiple root elements. Line 3, position 2." on the line reader.MoveToContent();
Below is the sample code that i use
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace sample
{
class Program
{
static void Main(string[] args)
{
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("C:\\Users\\ADMIN\\Pictures\\test.xml");
string contents = "";
while (reader.Read())
{
reader.MoveToContent();
if (reader.NodeType == System.Xml.XmlNodeType.Element)
contents += "<" + reader.Name + ">\n";
if (reader.NodeType == System.Xml.XmlNodeType.Text)
contents += reader.Value + "\n";
}
Console.Write(contents);
Console.ReadLine();
}
}
}
please help.
You are trying to parse an XML document, that, stand-alone, isn't valid XML. Therefore, you need to tell it that it is only a fragment. This will prevent it from throwing an error about multiple root elements.
You can do this by replacing the line
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("C:\\Users\\ADMIN\\Pictures\\test.xml");
with:
var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
var reader = System.Xml.XmlTextReader.Create("C:\\Users\\ADMIN\\Pictures\\test.xml", settings);

Add attribute to a Collection while reading csv file with CsvHelper

I use C# CsvHelper to read the following csv-file:
CSV-File Order:
ID;Message
0;Hello World
1;Foobar
My classes for the needed objects look like this. I need a collection of Text because after reading the csv file, I will add more messages to my Foobar object...
Foobar-Class:
public int ID {get;set;}
public ICollection<Text> Texts {get;set;}
public Foobar()
{
Texts = new List<Text>();
}
Text-Class:
public int ID {get;set;}
public string Message {get;set;}
My mapping for CsvHelper is
CsvClassMap of Foobar:
Map(m => m.ID).Index(0);
**Map(m => m.Texts).ConvertUsing(row => row.GetField<Text>("Message", 1));**
But Csvhelper doesn't add the message to Foobar's Collection. How can I achieve this?
Use my project below which adds the csv to a table. Then you can add rows to the table after the file is read.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Xml;
using System.Xml.Xsl;
namespace CSVImporter
{
public partial class CSVImporter : Form
{
//const string xmlfilename = #"C:\Users\fenwky\XmlDoc.xml";
const string xmlfilename = #"C:\temp\test.xml";
DataSet ds = null;
public CSVImporter()
{
InitializeComponent();
// Create a Open File Dialog Object.
openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialog1.ShowDialog();
string fileName = openFileDialog1.FileName;
//doc.InsertBefore(xDeclare, root);
// Create a CSV Reader object.
CSVReader reader = new CSVReader();
ds = reader.ReadCSVFile(fileName, true);
dataGridView1.DataSource = ds.Tables["Table1"];
}
private void WXML_Click(object sender, EventArgs e)
{
WriteXML();
}
public void WriteXML()
{
StringWriter stringWriter = new StringWriter();
ds.WriteXml(new XmlTextWriter(stringWriter), XmlWriteMode.WriteSchema);
string xmlStr = stringWriter.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr);
XmlDeclaration xDeclare = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.InsertBefore(xDeclare, doc.FirstChild);
// Create a procesing instruction.
//XmlProcessingInstruction newPI;
//String PItext = "<abc:stylesheet xmlns:abc=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">";
//String PItext = "type='text/xsl' href='book.xsl'";
string PItext = "html xsl:version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"";
XmlText newPI = doc.CreateTextNode(PItext);
//newPI = docCreateProcessingInstruction("html", PItext);
//newPI = doc.CreateComment(CreateDocumentType("html", PItext, "", "");
doc.InsertAfter(newPI, doc.FirstChild);
doc.Save(xmlfilename);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(xmlfilename);
string directoryPath = Path.GetDirectoryName(xmlfilename);
myXslTrans.Transform(xmlfilename, directoryPath + "result.html");
webBrowser1.Navigate(directoryPath + "result.html");
}
}
public class CSVReader
{
public DataSet ReadCSVFile(string fullPath, bool headerRow)
{
string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();
try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}
}

write xml file from data table ignoring columns with white spaces

I am trying to export the data from a data table into xml file. I have this part working but when a record does not have any data or a white space it still writes the it in the xml file with XML:space Preserved.
I want to ignore the columns and not have them in xml file if they do not have any data in them
example of the xml file it is producing now
I want customer street 3 and 4 nodes to be not printed if they don't have any values in them.
here is my code
using System.IO;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.Xml;
namespace InvoicePrintProgram
{
class XMLGenerator
{
//Defining method that generates XMl Files
public void Start(String XmlFilepath, string XMlFileName, DataTable DT, int PageCountOut, int SequenceCountOut, int[] PrefIndex/*, int[] SequenceIndex, IEnumerable<String> chunk, int IndexCount out int IndexCountOut*/)
{
// Creates Xml file from datatable using the wrtieXml method
FileStream streamWrite = new FileStream(XmlFilepath, System.IO.FileMode.Create);
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
//settings.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1")
settings.Encoding = System.Text.Encoding.UTF8;
settings.CloseOutput = true;
settings.CheckCharacters = true;
settings.NewLineChars = "\r\n";
DT.WriteXml(streamWrite, XmlWriteMode.IgnoreSchema);
You can create a List of Object from that DataTable and use something like this:
List<string> xml_string = new List<string>();
xml_string.Add("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml_string.Add("anything you need as header");
foreach(string current_string in your_object_of_DataTable)
{
if(current_string!=null || current_string.Trim()!="")
{
xml_string.Add("<Your Tag>"+current_string+"</Your Tag>");
}
}
try
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"D:\xml_file_name.xml"))
{
foreach (string line in xml_string)
{
file.WriteLine(line);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
MessageBox.Show("File exported.");
}

Convert .xlsx to .csv in asp net c#

I need convert the xlsx file to csv file and I have tried this article:
http://www.codeproject.com/Articles/246772/Convert-xlsx-xls-to-csv
The project works on ExcelDataReader library.
In local debug F5 with visual studio I don't have error and the conversion is worked, but If launch the aspx page on the server I have this error:
Compiler Error Message: CS0246: The type or namespace name 'Excel' could not be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 16: FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
Line 17:
Line 18: Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
Line 19: DataSet result = excelReader.AsDataSet();
Line 20: excelReader.Close();
What am I missing?
What's wrong with this code?
Thank you in advance.
using System;
using System.Data;
using System.IO;
public partial class Default2 : System.Web.UI.Page
{
DataSet result = new DataSet();
string filePath = #"\\...\Tbl.xlsx";
protected void UploadButton_Click(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + ",";
}
row_no++;
csvData += "\n";
}
string output = #"\\...\target.csv";
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(csvData);
csv.Close();
}
}
<add key="EXCEL" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="{0}";Extended Properties="Excel 8.0;HDR=NO;IMEX=1;"" />
You may need this entry in your web.config
I guess for using Excel object lib. you alredy installed the PIAs. If so, then the refrence will pointing to the GAC and not the local path. So in your using statement you need to give the full path(you can see the path thru the property of the added Excel reference in the VS)
Or You can use like
using Excel = Microsoft.Office.Interop.Excel
Refer: http://msdn.microsoft.com/en-IN/library/dd264733.aspx
You have created the virtual directory in IIS for project on the server ?
I don't really know what's the problem and it looks like you're tied since you can't install anything on the server.
I suggest to try to copy all the data in a .txt file and use the find/replace feature (or make a little console program that is going to replace every line of code)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImportComuni
{
class Program
{
static void Main(string[] args)
{
int i = 1;
StreamReader reader = File.OpenText("d:\\comunidatabase.txt");
StreamWriter writer = new StreamWriter("d:\\mysqlcomuni.csv");
string line = "";
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(i + "," + "\"" + line + "\"," + "\"" + a + "\"");
i++;
}
}
}
}
assuming the first line is a and the second is c, your output will be:
1, "a", "a"
2, "c", "c"
now you can copy these values in the INSERT INTO SQL or MySQL statement.
Otherwise create a notepad txt file, add the colons on the top of it:
id, name, country
1, "a", "a"
2, "c", "c"
and so on
now save it as "File.csv"
look at this for more informations about how to import your csv file, or manually insert your data
http://www.mysqltutorial.org/import-csv-file-mysql-table/

Search and retrieve xml in dataset?

I am trying to find some working examples to learn the wonders on Dataset with XML. Im using this example of the xml data. I want to search through all the CD nodes for the TITLE value.
DataSet dsXml = new DataSet();
dsXml.ReadXml(msXml);
look at using linq2xml. you could also use linq to "query" the dataset. http://msdn.microsoft.com/en-us/vbasic/bb688086.aspx
Here is a very simple C# code which will print all the "TITLE" in the provided XML:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataSet dsXml = new DataSet();
dsXml.ReadXml("http://www.w3schools.com/xml/cd_catalog.xml");
for (int i = 0; i < dsXml.Tables.Count; i++)
{
Console.WriteLine("Table Name: " + dsXml.Tables[i].TableName);
int j = 1;
foreach (DataRow myRow in dsXml.Tables[i].Rows)
{
Console.Write("[" + j++ + "]");
foreach (DataColumn myColumn in dsXml.Tables[i].Columns)
{
if (myColumn.ColumnName.Equals("TITLE"))
Console.Write("[" + myRow[myColumn] + "]");
}
Console.WriteLine("");
}
}
}
}
}

Categories

Resources