Search and retrieve xml in dataset? - c#

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("");
}
}
}
}
}

Related

Accessing variable in another namespace C#

I know this has been discussed many times on here, I've tried to set my variables as public etc. but I can't seem to be able to use it in my other name space. I'd appreciate if you could give me some tips (I'm a noob at C#)
The string i'm trying access from my other name space is "stringatlinei"
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Net.Mail;
using ConsoleApplication32;
namespace ConsoleApplication32
{
public class Program
{
static void Main(string[] args)
{
DirSearch(#"C:\\Users\\");
Console.ReadKey();
}
static void DirSearch(string dir)
{
try
{
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d);
// Compose a string that consists of three lines.
string lines = d;
// Write the string to a file.
System.IO.StreamWriter file = new
System.IO.StreamWriter("c:\\users\\chris\\desktop\\test.txt", true);
file.WriteLine(lines);
file.Close();
var oldLines = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines = oldLines.Where(line => !line.Contains("Windows"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines);
var oldLines4 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines4 = oldLines.Where(line => !line.Contains("$Recycle.Bin"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines4);
var oldLines7 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines7 = oldLines.Where(line => !line.Contains("Program Files"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines7);
var oldLines8 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines8 = oldLines.Where(line => !line.Contains("Program Files (x86)"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines8);
var oldLines9 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines9 = oldLines.Where(line => !line.Contains("AppData"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines9);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
var lineCount = File.ReadLines(#"c:\\users\\chris\\desktop\\test.txt").Count();
Console.WriteLine(lineCount);
Console.ReadLine();
int element = 0;
for (int i = 0; i < lineCount + 1; i++)
{
element = element + 1;
String stringAtLinei = File.ReadLines("c:\\users\\chris\\desktop\\test.txt").ElementAtOrDefault(element);
Console.WriteLine(stringAtLinei);
}
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "random command example thing";
process.StartInfo = startInfo;
process.Start();
}
}
}
then the other namespace etc.
"stringatlinei" is not a property, or a public anything, it is defined inside a loop inside a function.
Try public static string stringatlinei="", then just assign in your loop.
Accessing that variable in another namespace is not possible. You should read up on the basics, scope in particular, to understand why this is so. Here's a helpful article: https://msdn.microsoft.com/en-us/library/aa691132(v=vs.71).aspx
Basically, your variable you are trying access is created inside your for loop. Each iteration of your loop, it goes away.
Here's the part you should change: (I removed the rest for clarity)
namespace ConsoleApplication32
{
public class Program
{
public String stringAtLinei;
static void DirSearch(string dir)
{
for (int i = 0; i < lineCount + 1; i++)
{
stringAtLinei = File.ReadLines("c:\\users\\chris\\desktop\\test.txt").ElementAtOrDefault(element);
}
}
}
}
The point is that you can access fields and properties of a class, but not variables that are confined to the method they're in. So I changed the variable to be a field in the class.

Display the data of two xml codes in c# datagridview?

I have two xml codes that display the data from two seperate tables, now i want to read both of them in c# and display the data from join of them
I've tried this one but it just works for one table.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/ShowUsers.php");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader input = new StreamReader(response.GetResponseStream());
ds.ReadXml(input);
try
{
int varTotCol = ds.Tables[0].Columns.Count, varTotRow = ds.Tables[0].Rows.Count;
frm.dgv_ShowUsers.DataSource = ds.Tables["users"];
}
catch (Exception Except)
{
MessageBox.Show(Except.ToString());
}
And these are my xml codes:
//first one
<users>
<ID>1</ID>
<user_login>admin</user_login>
<user_pass>$P$Bdfdffddkjlkiyuyadnvjd</user_pass>
<term_id>2</term_id>
<user_activation_key></user_activation_key>
<user_status>0</user_status>
<display_name>admin</display_name>
<users>
//second one
<terms>
<term_id>2</term_id>
<name>name</name>
<term_group>0</term_group>
</terms>
I've convert my database to this xml code via php, I don't know if I should write it here too or not.
Now how should i change the c# code above to work for two or more tables?
Thanks beforehand and sorry for my english.
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml1 =
"<root>" +
"<users>" +
"<ID>1</ID>" +
"<user_login>admin</user_login>" +
"<user_pass>$P$Bdfdffddkjlkiyuyadnvjd</user_pass>" +
"<term_id>2</term_id>" +
"<user_activation_key></user_activation_key>" +
"<user_status>0</user_status>" +
"<display_name>admin</display_name>" +
"</users>" +
"</root>";
XElement users = XElement.Parse(xml1);
string xml2 =
"<root>" +
"<terms>" +
"<term_id>2</term_id>" +
"<name>name</name>" +
"<term_group>0</term_group>" +
"</terms>" +
"</root>";
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Login", typeof(string));
dt.Columns.Add("Password", typeof(string));
dt.Columns.Add("TermID", typeof(int));
dt.Columns.Add("Key", typeof(string));
dt.Columns.Add("Status", typeof(int));
dt.Columns.Add("DisplayName", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Group", typeof(int));
XElement terms = XElement.Parse(xml2);
try
{
var groups = from user in users.Elements("users")
join term in terms.Elements("terms")
on (int)user.Element("term_id") equals (int)term.Element("term_id")
select new { user = user, term = term };
foreach (var group in groups)
{
dt.Rows.Add(new object[] {
(int)group.user.Element("ID"),
(string)group.user.Element("user_login"),
(string)group.user.Element("user_pass"),
(int)group.user.Element("term_id"),
(string)group.user.Element("user_activation_key"),
(int)group.user.Element("user_status"),
(string)group.user.Element("display_name"),
(string)group.term.Element("Name"),
(int)group.term.Element("term_group")
});
}
frm.dgv_ShowUsers.DataSource = dt;
}
catch (Exception e)
{
}
}
}
}
Here is a dynamic solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml1Str =
"<root>" +
"<users>" +
"<ID>1</ID>" +
"<user_login>admin</user_login>" +
"<user_pass>$P$Bdfdffddkjlkiyuyadnvjd</user_pass>" +
"<term_id>2</term_id>" +
"<user_activation_key></user_activation_key>" +
"<user_status>0</user_status>" +
"<display_name>admin</display_name>" +
"</users>" +
"</root>";
XElement xml1 = XElement.Parse(xml1Str);
XElement xml1FirstNode = (XElement)xml1.FirstNode;
string[] xml1ColNames = xml1FirstNode.Elements().Select(x => x.Name.LocalName).ToArray();
string xml2Str =
"<root>" +
"<terms>" +
"<term_id>2</term_id>" +
"<name>name</name>" +
"<term_group>0</term_group>" +
"</terms>" +
"</root>";
XElement xml2 = XElement.Parse(xml2Str);
XElement xml2FirstNode = (XElement)xml2.FirstNode;
string[] xml2ColNames = xml2FirstNode.Elements().Select(x => x.Name.LocalName).ToArray();
DataTable dt = new DataTable();
string[] colNames = xml1ColNames.Union(xml2ColNames).ToArray();
foreach (var colName in colNames)
{
dt.Columns.Add(colName, typeof(string));
}
try
{
var groups = from x1 in xml1.Elements()
join x2 in xml2.Elements()
on (string)x1.Element("term_id") equals (string)x2.Element("term_id")
select new { x1 = x1, x2 = x2 };
foreach (var group in groups)
{
DataRow newRow = dt.Rows.Add();
foreach (var x1Value in group.x1.Elements())
{
newRow[x1Value.Name.LocalName] = (string)x1Value;
}
foreach (var x2Value in group.x2.Elements())
{
newRow[x2Value.Name.LocalName] = (string)x2Value;
}
}
frm.dgv_ShowUsers.DataSource = dt;
}
catch (Exception e)
{
}
}
}
}

How do I populate an array with foreach?

How do I get the data I can write in the console to write to the array and the console.
At the moment it only displays on the console (not added functionality to add to array).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace TBParser
{
class Program
{
static void Main(string[] args)
{
String[] arr = new String[100];
string[] lines = System.IO.File.ReadAllLines(#"C:\ShpereCompare3.txt");
Console.WriteLine("Contents of Text File: ");
foreach (string line in lines)
{
Console.WriteLine("\r\t" + line);
}
System.IO.File.WriteAllLines(#"C:\Test.txt",lines);
Console.WriteLine("Press any key to Exit");
Console.ReadKey();
}
}
}
if my lines of text say
hello
my
name
is
Simon
then the first 5 slots of the array should contain each line?
The line:
string[] lines = System.IO.File.ReadAllLines(#"C:\ShpereCompare3.txt");
is already creating an array, each element of which contains one line.
There is no need to populate a new array with this same information via a foreach.
If you want to copy the lines from the text file into another array, then you can do this:
String[] arr = new String[lines.Length];
Array.Copy(lines, arr, lines.Length);
found a work around. the path i was going down was too complicated. thanks for all your input
fixed code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace TBParser
{
class Program
{
static void Main(string[] args)
{
string fileName = #"C:shpereCompare3.txt";
List<string> Names = new List<string>();
List<string> Value = new List<string>();
using (StreamReader fileReader = new StreamReader(fileName))
{
string fileLine;
while (!fileReader.EndOfStream)
{
fileLine = fileReader.ReadLine();
if (fileLine.StartsWith("Name"))
{
Names.Add(fileLine.Substring(21));
}
if (fileLine.StartsWith("Center"))
{
string[] fileSplit = fileLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Value.Add(fileSplit[1]);
}
}
string outputString = "";
for (int i = 0;i < Names.Count; i++)
{
outputString += Names[i] + " = " + Value[i] + "\r\n";
}
System.IO.File.WriteAllText(#"C:Test.txt", outputString);
}
}
}
}

Random memory leak while reading xlsx files using C#

I am new to C# and wpf but am trying to read a lot of data (abt. 40000 x 34 cells) from +100 xlsx files and concatenate them into a text file.
I have made a small C# (wpf) app to do that. I see somewhat random memory leak, where sometimes as I run it, everything goes well and the memory it requires (according to windows task manager) stays under 1 GB, while other times it eats, almost all of my 8 GB.
One situation I have found happens when using System.IO.File.ReadAllLines(pathtotextfilewithxlsxfilenames)
whereas using the discreet example (specifying the filenames in the code) does not in the same way seem to cause the problem. (I have copied and pasted the same names from the text file with xlsx-filenames to the code (replaced tabs with ", ") so it should be equal.. as far as I understand).
The app is roughly like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.IO;
using System.Data.OleDb;
namespace WpfApps
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string s_path_to_list_of_xlsx_files;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
string path = #"F:\...\xls_files\";
string[] fnlist = { "datafile1.xlsx", "datafile2.xlsx", ... "datafileN.xlsx" };
//string[] fnlist = System.IO.File.ReadAllLines(#"f:\...\xlsfiles.txt"); // It seems as if using this line, compared to the discreet line above causes memory leak.
DataTable measurementdata = new DataTable();
measurementdata.Columns.Add("C1", typeof(double));
measurementdata.Columns.Add("C2", typeof(double));
...
measurementdata.Columns.Add("C34", typeof(double));
using (StreamWriter sw = File.CreateText(path + "allresult.txt"))
{
bool firstCol = true;
foreach (DataColumn col in measurementdata.Columns)
{
if (!firstCol) sw.Write(", ");
sw.Write(col.ColumnName);
firstCol = false;
}
sw.WriteLine();
}
foreach (var fn in fnlist)
{
DataTable filedt = GetDataTableFromExcel(path + fn, false);
using (StreamWriter sw = File.AppendText(path + "allresult.txt"))
{
foreach (DataRow row in filedt.Rows)
{
bool firstCol = true;
foreach (DataColumn col in filedt.Columns)
{
if (!firstCol) sw.Write(", ");
sw.Write(row[col].ToString());
firstCol = false;
}
sw.WriteLine();
}
}
}
}
public static DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets["Logged Data"];
int startrow = 72;
int endrow = 43271;
DataTable tbl = new DataTable();
foreach (var firstrowcell in ws.Cells[startrow - 1, 8, startrow - 1, 41])
{
tbl.Columns.Add(firstrowcell.Text);
}
for (int rowNum = startrow; rowNum <= endrow; rowNum++)
{
var wsRow = ws.Cells[rowNum, 8, rowNum, 41];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
var cellvalue = cell.Value;
if (cellvalue == null) cellvalue = "0";
row[cell.Start.Column - 8] = cellvalue;
}
}
return tbl;
}
}
Can anyone see an obvious problem?

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.");
}

Categories

Resources