I want to generate an xml file in the fllowing format.
<?xml version="1.0" encoding="utf-8"?>
<AutoCount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.autocountsoft.com/ac_accounting.xsd">
<Product>AutoCount Accounting</Product>
<Version>1.5</Version>
<CreatedApplication>BApp</CreatedApplication>
<CreatedBy>Business Solutions</CreatedBy>
<Sales DocNo = 'S0001'>
<Item>XXX</Item>
<Qty>2</Qty>
<Price>6.00</Price>
</Sales>
<Sales DocNo = 'S0002'>
<Item>YYY</Item>
<Qty>3</Qty>
<Price>50.00</Price>
</Sales>
</AutoCount>
I have a grid with four columns Docno,item,qty,price and two rows of data.
but i get only one sales node with last row data in grid.
Code i tried is as follows,
string PATH = "C:\\Samplex.xml";
CreateEmptyFile(PATH);
var data = new AutoCount();
data.Product = "AutoCount Accounting";
data.Version = "1.5";
data.CreatedApplication = "BApp";
data.CreatedBy = "Business Solutions";
data.CreatedDateTime = DateTime.Now;
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
var sales = new SalesInvoice();
data.SalesInvoice = new[] { sales };
sales.DocNo = dataGridView1.Rows[i].Cells[0].FormattedValue.ToString();
sales.Item = dataGridView1.Rows[i].Cells[1].FormattedValue.ToString();
sales.Qty = dataGridView1.Rows[i].Cells[2].FormattedValue.ToString();
sales.Price = dataGridView1.Rows[i].Cells[3].FormattedValue.ToString();
var serializer1 = new XmlSerializer(typeof(SalesInvoice));
}
var serializer = new XmlSerializer(typeof(AutoCount));
using (var stream = new StreamWriter(PATH))
serializer.Serialize(stream, data);
Output was:
<?xml version="1.0" encoding="utf-8"?>
<AutoCount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.autocountsoft.com/ac_accounting.xsd">
<Product>AutoCount Accounting</Product>
<Version>1.5</Version>
<CreatedApplication>BApp</CreatedApplication>
<CreatedBy>Business Solutions</CreatedBy>
<Sales DocNo = 'S0002'>
<Item>YYY</Item>
<Qty>3</Qty>
<Price>50.00</Price>
</Sales>
</AutoCount>
Among other problems, the main one is here:
data.SalesInvoice = new[] { sales };
You create the SalesInvoice array from scratch at evey cycle loop, instead of creating it before the cycle and adding elements inside it.
Here's how I would do (look at variable names too please):
//Plural as it is a list
List<SalesInvoice> salesInvoices = new List<SalesInvoice>();
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
//Singular as it is a single element
var salesInvoice = new SalesInvoice();
salesInvoice.DocNo = dataGridView1.Rows[i].Cells[0].FormattedValue.ToString();
salesInvoice.Item = dataGridView1.Rows[i].Cells[1].FormattedValue.ToString();
salesInvoice.Qty = dataGridView1.Rows[i].Cells[2].FormattedValue.ToString();
salesInvoice.Price = dataGridView1.Rows[i].Cells[3].FormattedValue.ToString();
salesInvoices.Add(salesInvoice);
//What's the purpose of the next line?
var serializer1 = new XmlSerializer(typeof(SalesInvoice));
}
// I pluralized this property name too
data.SalesInvoices = salesInvoices.ToArray();
Use a DataSet/DataTable and the program becomes trivial. Add two datagridviews to your form.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string FILENAME = #"c:\temp\test.xml";
AutoCount autoCount = new AutoCount();
public Form1()
{
InitializeComponent();
autoCount.ds.WriteXml(FILENAME, XmlWriteMode.WriteSchema);
dataGridView1.DataSource = autoCount.ds.Tables["AutoCount"];
dataGridView2.DataSource = autoCount.ds.Tables["Sales"];
}
public class AutoCount
{
public DataSet ds {get; set;}
public AutoCount()
{
ds = new DataSet();
DataTable autoCount = new DataTable("AutoCount");
ds.Tables.Add(autoCount);
DataTable sales = new DataTable("Sales");
ds.Tables.Add(sales);
autoCount.Columns.Add("Product", typeof(string));
autoCount.Columns.Add("Version", typeof(string));
autoCount.Columns.Add("CreatedApplication", typeof(string));
autoCount.Columns.Add("CreatedBy", typeof(string));
autoCount.Rows.Add(new string[] {
"AutoCount Accounting",
"1.5",
"BApp",
"Business Solutions"
});
sales.Columns.Add("DocNo", typeof(string));
sales.Columns.Add("Item", typeof(string));
sales.Columns.Add("Qty", typeof(int));
sales.Columns.Add("Price", typeof(double));
sales.Rows.Add(new object[] {
"S0001",
"XXX",
2,
6.00
});
sales.Rows.Add(new object[] {
"S0002",
"YYY",
3,
50.00
});
}
}
}
}
Related
I am getting this error message n Visual Studio: "Could not find Schema Information Number, Name, Period, a0 and aJ." I have a working schema "SemiMajorAxis.xsd" but I do not know how to use it. Later in the program I deal with the DataTable
SemiMajorAxis.aspx.cs
DataSet dsread = new DataSet();
DataTable dtread = new DataTable();
dsread.ReadXml(Server.MapPath("SemiMajorAxis.xml"));
dtread = dsread.Tables[0];
XDocument xmldoc = XDocument.Load(Server.MapPath("SemiMajorAxis.xml"));
var elements = from data in xmldoc.Descendants("planet")
select new
{
Numberp = (int)data.Element("Number"),
Namep = (string)data.Element("Name"),
Pyrsp = (double)data.Element("Period"),
a0p = (double)data.Element("a0"),
aJp = (double)data.Element("aJ")
};
foreach (var element in elements)
{
m = m + 1;
num[m] = element.Numberp;
name[m] = element.Namep;
a0[m] = element.a0p;
aJ[m] = element.aJp;
a[m] = a0[m] + aJ[m] * J;
}
SemiMajorAxis.xml
<?xml version="1.0" standalone="yes"?>
<planets>
<planet>
<Number>1</Number>
<Name>Mercury</Name>
<Period>0.2408</Period>
<a0>0.38709893</a0>
<aJ>0.00000066</aJ>
</planet>
<planet>
<Number>2</Number>
<Name>Venus</Name>
<Period>0.6152</Period>
<a0>0.72333199</a0>
<aJ>0.00000092</aJ>
</planet>
<planet>
<Number>3</Number>
<Name>Earth</Name>
<Period>1</Period>
<a0>1.00000011</a0>
<aJ>-0.00000005</aJ>
</planet>
</planets>
So I have a directory with many XML files. I tried to show dataset in datagirdview but not enough content, someone please help me show all the content in the file
Below is the code and XML I used.
<?xml version="1.0" encoding="UTF-8"?>
<ns1:BoardTestXMLExport numberOfIndictedComponents="4" testerTestStartTime="2021-01-18T07:46:32.000+07:00" testTime="2021-01-18T07:46:24.000+07:00" repairStationId="VNHCMING100" testStatus="Repaired" testerTestEndTime="2021-01-18T07:46:37.000+07:00" xmlns:ns1="http://tempuri.org/BoardTestXMLExport.xsd" numberOfIndictedPins="0" numberOfComponentsTested="320" numberOfJointsTested="0" numberOfDefects="4" repairStatus="Repaired">
<ns1:BoardXML imageId="3" serialNumber="21017227600" assemblyRevision="ING-296269012AC-A-B" boardType="ING-296269012AC-A-B" boardRevision="1610927415000"/>
<ns1:StationXML testerName="HCMINGAOI02" stage="V510"/>
<ns1:RepairEventXML numberOfVariationOkDefects="0" numberOfFalseCalledPins="0" numberOfRepairedComponents="2" numberOfVariationOkPins="0" numberOfRepairedPins="0" numberOfRepairLaterPins="0" numberOfFalseCalledDefects="2" numberOfActiveDefects="0" numberOfVariationOkComponents="0" repairEndTime="2021-01-18T07:49:24.000+07:00" repairStartTime="2021-01-18T07:49:10.000+07:00" numberOfRepairLaterDefects="0" repairOperator="c_admin" numberOfRepairLaterComponents="0" numberOfActiveComponents="0" numberOfActivePins="0" numberOfRepairedDefects="2" numberOfFalseCalledComponents="2"/>
<ns1:TestXML name="3:hp1400">
<ns1:IndictmentXML algorithm="u192036979" indictmentType="Wrong Polarity">
<ns1:RepairActionXML repairOperator="c_admin" repairTime="2021-01-18T07:49:11.000+07:00" repairActionType="-" indictmentType="Wrong Polarity" comment="-" repairStatus="False Call"/>
<ns1:ComponentXML packageId="192036979" partId="192036979" designator="3:hp1400"/>
</ns1:IndictmentXML>
</ns1:TestXML>
<ns1:TestXML name="3:d506">
<ns1:IndictmentXML algorithm="u192027714" indictmentType="Wrong Polarity">
<ns1:RepairActionXML repairOperator="c_admin" repairTime="2021-01-18T07:49:11.000+07:00" repairActionType="-" indictmentType="Wrong Polarity" comment="-" repairStatus="False Call"/>
<ns1:ComponentXML packageId="192027714" partId="192027714" designator="3:d506"/>
</ns1:IndictmentXML>
</ns1:TestXML>
<ns1:TestXML name="3:j1201">
<ns1:IndictmentXML algorithm="u192030753" indictmentType="Skewed">
<ns1:RepairActionXML repairOperator="c_admin" repairTime="2021-01-18T07:49:17.000+07:00" repairActionType="-" indictmentType="Skewed" comment="-" repairStatus="Repaired"/>
<ns1:ComponentXML packageId="192030753" partId="192030753" designator="3:j1201"/>
</ns1:IndictmentXML>
</ns1:TestXML>
<ns1:TestXML name="3:u2101">
<ns1:IndictmentXML algorithm="u192028597" indictmentType="Tombstoned">
<ns1:RepairActionXML repairOperator="c_admin" repairTime="2021-01-18T07:49:24.000+07:00" repairActionType="-" indictmentType="Tombstoned" comment="-" repairStatus="Repaired"/>
<ns1:ComponentXML packageId="192028597" partId="192028597" designator="3:u2101"/>
</ns1:IndictmentXML>
</ns1:TestXML>
</ns1:BoardTestXMLExport>
Code:
foreach (string FILE_PATH in Directory.EnumerateFiles(#"Test", "*.xml"))
{
//Create xml reader
XmlReader xmlFile = XmlReader.Create(FILE_PATH, new XmlReaderSettings());
DataSet dataSet = new DataSet();
//Read xml to dataset
dataSet.ReadXml(xmlFile);
//Pass empdetails table to datagridview datasource
dataGridView1.DataSource = dataSet.Tables["BoardTestXMLExport"];
//Close xml reader
xmlFile.Close();
xmlFile.Close();
}
Try following xml linq :
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.Xml;
using System.Xml.Linq;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
const string FOLDER = #"c:\temp\";
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("filename", typeof(string));
dt.Columns.Add("numberOfIndictedComponents", typeof(int));
dt.Columns.Add("testerTestStartTime", typeof(DateTime));
dt.Columns.Add("testTime", typeof(DateTime));
dt.Columns.Add("repairStationId", typeof(string));
dt.Columns.Add("testStatus", typeof(string));
dt.Columns.Add("testerTestEndTime", typeof(DateTime));
dt.Columns.Add("imageId", typeof(string));
dt.Columns.Add("serialNumber", typeof(string));
dt.Columns.Add("assemblyRevision", typeof(string));
dt.Columns.Add("boardType", typeof(string));
dt.Columns.Add("boardRevision", typeof(string));
dt.Columns.Add("testerName", typeof(string));
dt.Columns.Add("stage", typeof(string));
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("algorithm", typeof(string));
dt.Columns.Add("indictmentType", typeof(string));
dt.Columns.Add("repairOperator", typeof(string));
dt.Columns.Add("repairTime", typeof(DateTime));
dt.Columns.Add("repairActionType", typeof(string));
dt.Columns.Add("comment", typeof(string));
dt.Columns.Add("repairStatus", typeof(string));
dt.Columns.Add("packageId", typeof(string));
dt.Columns.Add("partId", typeof(string));
dt.Columns.Add("designator", typeof(string));
string[] filenames = Directory.GetFiles(FOLDER,"*.xml");
foreach (string filename in filenames)
{
XDocument doc = XDocument.Load(filename);
XElement BoardTestXMLExport = doc.Root;
XNamespace ns1 = BoardTestXMLExport.GetNamespaceOfPrefix("ns1");
int numberOfIndictedComponents = (int)BoardTestXMLExport.Attribute("numberOfIndictedComponents");
DateTime testerTestStartTime = (DateTime)BoardTestXMLExport.Attribute("testerTestStartTime");
DateTime testTime = (DateTime)BoardTestXMLExport.Attribute("testTime");
string repairStationId = (string)BoardTestXMLExport.Attribute("repairStationId");
string testStatus = (string)BoardTestXMLExport.Attribute("testStatus");
DateTime testerTestEndTime = (DateTime)BoardTestXMLExport.Attribute("testerTestEndTime");
XElement BoardXML = BoardTestXMLExport.Element(ns1 + "BoardXML");
int imageId = (int)BoardXML.Attribute("imageId");
string serialNumber = (string)BoardXML.Attribute("serialNumber");
string assemblyRevision = (string)BoardXML.Attribute("assemblyRevision");
string boardType = (string)BoardXML.Attribute("boardType");
string boardRevision = (string)BoardXML.Attribute("boardRevision");
XElement StationXML = BoardTestXMLExport.Element(ns1 + "StationXML");
string testerName = (string)StationXML.Attribute("testerName");
string stage = (string)StationXML.Attribute("stage");
foreach (XElement TestXML in doc.Descendants(ns1 + "TestXML"))
{
DataRow newRow = dt.Rows.Add();
newRow["filename"] = filename;
newRow["numberOfIndictedComponents"] = numberOfIndictedComponents;
newRow["testerTestStartTime"] = testerTestStartTime;
newRow["testTime"] = testTime;
newRow["repairStationId"] = repairStationId;
newRow["testStatus"] = testStatus;
newRow["testerTestEndTime"] = testerTestEndTime;
newRow["imageId"] = imageId;
newRow["serialNumber"] = serialNumber;
newRow["assemblyRevision"] = assemblyRevision;
newRow["boardType"] = boardType;
newRow["boardRevision"] = boardRevision;
newRow["boardType"] = boardType;
newRow["testerName"] = testerName;
newRow["stage"] = stage;
newRow["name"] = (string)TestXML.Attribute("name");
XElement IndictmentXML = TestXML.Element(ns1 + "IndictmentXML");
newRow["algorithm"] = (string)IndictmentXML.Attribute("algorithm");
newRow["indictmentType"] = (string)IndictmentXML.Attribute("indictmentType");
XElement RepairActionXML = TestXML.Descendants(ns1 + "RepairActionXML").FirstOrDefault();
newRow["repairOperator"] = (string)RepairActionXML.Attribute("repairOperator");
newRow["repairTime"] = (DateTime)RepairActionXML.Attribute("repairTime");
newRow["repairActionType"] = (string)RepairActionXML.Attribute("repairActionType");
newRow["comment"] = (string)RepairActionXML.Attribute("comment");
newRow["repairStatus"] = (string)RepairActionXML.Attribute("repairStatus");
XElement ComponentXML = TestXML.Descendants(ns1 + "ComponentXML").FirstOrDefault();
newRow["packageId"] = (string)ComponentXML.Attribute("packageId");
newRow["partId"] = (string)ComponentXML.Attribute("partId");
newRow["designator"] = (string)ComponentXML.Attribute("designator");
}
}
dataGridView1.DataSource = dt;
}
}
}
looks like a very simple task by i'm very new to c# and can't seem to find the right answer for this
i have the below xml structure (elements vary in quantity)
<config>
<extras>
<dir_update>C:\extension\update.exe</dir_update>
</extras>
<connection_MAIN>
<ip>LOCALHOST,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>gzqs=</password>
</connection_MAIN>
<connection_LOBBY>
<ip>10.0.0.2,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
<caixa>5yIz5GPu80s=</caixa>
<printer>cARrmGLQlztLiUDxIJqoPkvJabIiyI9ye4H7t+4muYk=</printer>
</connection_LOBBY>
<connection_FRONT>
<ip>10.0.0.5,1433</ip>
<bd>FIELDS</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
</connection_FRONT>
</config>
I'm already getting the elements that start with "connection_" in my combobox and i want the values inside the <ip>, <bd>, <user> and <password> when i select the connection on the combobox.
The problem i'm getting is that it's returning the word itself not the value inside on the code below
private void Form1_Load(object sender, EventArgs e)
{
using(DataSet ds = new DataSet())
{
ds.ReadXml(textBox1.Text);
foreach(DataTable dt in ds.Tables)
{
if (dt.ToString().Contains("conection_"))
{
comboBox1.Items.Add(dt.ToString().Replace("conection_", ""));
}
}
comboBox1.SelectedIndex = 0;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using(DataSet ds = new DataSet())
{
ds.ReadXml(textBox1.Text);
string v = comboBox1.Text.ToString();
string ip = ds.Tables[$"conection_{v}"].Columns[0].ToString();
}
}
Variable ip is getting the value "ip" and i want "LOCALHOST,1433" when i select the first option on my combobox in this example.
Also i want to search for column value by the name ("ip", "bd"), but i seem to only get results when using Columns[0], Columns[1].
I've followed some guides that i've looked around, but they seem to not work on this format of xml or i'm looking at it the wrong way.
Any help is appreciated.
There is no need to use DataSet and DataTable data types. The best API to handle XML is LINQ to XML.
Check it out below.
c#
void Main()
{
const string MAIN = "connection_MAIN";
string IP = string.Empty;
string bd = string.Empty;
string user = string.Empty;
string password = string.Empty;
XElement xml = XElement.Parse(#"<config>
<extras>
<dir_update>C:\extension\update.exe</dir_update>
</extras>
<connection_MAIN>
<ip>LOCALHOST,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>gzqs=</password>
</connection_MAIN>
<connection_LOBBY>
<ip>10.0.0.2,1433</ip>
<bd>DATA</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
<caixa>5yIz5GPu80s=</caixa>
<printer>cARrmGLQlztLiUDxIJqoPkvJabIiyI9ye4H7t+4muYk=</printer>
</connection_LOBBY>
<connection_FRONT>
<ip>10.0.0.5,1433</ip>
<bd>FIELDS</bd>
<user>sa</user>
<password>I/wqqZIgzqs=</password>
</connection_FRONT>
</config>");
// get needed connection fragment
IEnumerable<XElement> fragment = xml.Descendants(MAIN);
// get all needed elements one by one
IP = fragment.Elements("ip")?.FirstOrDefault().Value;
bd = fragment.Elements("bd")?.FirstOrDefault().Value;
user = fragment.Elements("user")?.FirstOrDefault().Value;
password = fragment.Elements("password")?.FirstOrDefault().Value;
}
Using Xml Linq I put results in to a datatable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("ip", typeof(string));
dt.Columns.Add("bd", typeof(string));
dt.Columns.Add("user", typeof(string));
dt.Columns.Add("password", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
foreach(XElement connection in doc.Descendants().Where(x => x.Name.LocalName.StartsWith("connection_")))
{
dt.Rows.Add(new object[] {
((string)connection.Name.LocalName).Substring(((string)connection.Name.LocalName).IndexOf("_") + 1),
(string)connection.Element("ip"),
(string)connection.Element("bd"),
(string)connection.Element("user"),
(string)connection.Element("password")
});
}
Dictionary<string, DataRow> dict = dt.AsEnumerable()
.GroupBy(x => x.Field<string>("name"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
string ip = dict["LOBBY"].Field<string>("ip");
}
}
}
Here is my schema of xml.
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfResultstring xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Resultstring>
<Key>Blablabla : </Key>
<Values>
<string>79,0441326460292</string>
<string>76,0959542079328</string>
<string>74,3061819154758</string>
<string>78,687039788779</string>
</Values>
<Type>list</Type>
</Resultstring>
<Resultstring>
<Key>Blablabla : </Key>
<Values>
<string>87,7110395931923</string>
</Values>
<Type>double</Type>
</Resultstring>
</ArrayOfResultstring>
I need read this XML file and fill the datatable.
I'm trying with DataSet.
DataSet ds = new DataSet();
ds.ReadXml(path);
DataTable dt = ds.Tables[0];
And my output datatable is like.
I need to show my items on table. Is there any way to read properly ?
Try following xml linq which creates a separate row for each string :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication51
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("KEY", typeof(string));
dt.Columns.Add("RESULTING_ID", typeof(string));
dt.Columns.Add("TYPE", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
foreach (XElement resultingString in doc.Descendants(ns + "Resultstring"))
{
string key = (string)resultingString.Element("Key");
string type = (string)resultingString.Element("Type");
string ids = string.Join(";", resultingString.Descendants("string").Select(x => (string)x));
dt.Rows.Add(new object[] { key, ids, type });
}
}
}
}
Code to put each string in a separate column
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication51
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement root = doc.Root;
XNamespace ns = root.GetDefaultNamespace();
int maxString = doc.Descendants(ns + "Resultstring").Select(x => x.Descendants("string").Count()).Max();
DataTable dt = new DataTable();
dt.Columns.Add("KEY", typeof(string));
dt.Columns.Add("TYPE", typeof(string));
for (int i = 0; i < maxString; i++)
{
dt.Columns.Add("RESULTING_ID_" + (i + 1).ToString(), typeof(string));
}
foreach (XElement resultingString in doc.Descendants(ns + "Resultstring"))
{
string key = (string)resultingString.Element("Key");
string type = (string)resultingString.Element("Type");
List<string> row = resultingString.Descendants("string").Select(x => (string)x).ToList();
row.Insert(0, key);
row.Insert(1, type);
dt.Rows.Add(row.ToArray());
}
}
}
}
With Cinchoo ETL - an open source library, you can easily convert Xml file to DataTable with few lines of code.
For your sample xml file, you can extract the data into datatable as below
using (var p = new ChoXmlReader(** YOUR XML FILE **)
.WithField("Key")
.WithField("Value", xPath: "/Values/string")
)
{
var dt = p.SelectMany(r => ((Array)r.Value).OfType<string>().Select(r1 => new { Key = r.Key, Value = r1})).AsDataTable();
}
Output:
Hope it helps.
your Resultstring xml node is repeating. Below code is working for me
<Resultstring>
<Key>Blablabla : </Key>
<Values>
<string>79,0441326460292</string>
<string>76,0959542079328</string>
<string>74,3061819154758</string>
<string>78,687039788779</string>
</Values>
<Type>list</Type>
<Key>Blablabla : </Key>
<Values>
<string>87,7110395931923</string>
</Values>
<Type>double</Type>
</Resultstring>
Dataset code
DataSet ds = new DataSet();
ds.ReadXml(path);
DataTable dtKey = ds.Tables[0];
DataTable dtValues = ds.Tables[1];
DataTable dtstring = ds.Tables[2];
DataTable dtType = ds.Tables[3];
I want to get all the data from a table using the code below:
CameraBUS cameraBus = new CameraBUS(); //Contain class provider access to DAO for GetByAllCamera.
DataTable dt = cameraBus.Camera_GetByAllCamera(); //select * from table Camera
foreach (DataRow row in dt.Rows)
{
CameraDTO camera = new CameraDTO(row);
if(camera.IDKhuVuc == 4)
{
OpenCamera(camera.ViTri, camera.TaiKhoan, camera.MatKhau, camera.IP);
}
if(camera.IDKhuVuc == 3)
{
OpenCamera(camera.ViTri, camera.TaiKhoan, camera.MatKhau, camera.IP);
}
}
If camera.IDKhuVuc have 7 rows or more. It's always start StartThead1 and my program stop not working.
Example:
My data has 4 rows, but this code can't get 4 rows of 4 cameras. It only opens the first and last cameras.
When I debug my program, it runs 2 rows (rows 2, 3). But when I run my program, it's not opening camera 2 and camera 3.
I think I should use List<> or array. How could I fix this?
Class OpenCamera():
private void OpenCamera(bool position, string username, string password, string ipAddress)
{
if (!position)
{
axLiveX1.IpAddress = ipAddress;
axLiveX1.UserName = username;
axLiveX1.Password = password;
axLiveX1.DataPort = 5550;
axLiveX1.CommandPort = 4550;
axLiveX1.AudioDataPort = 6550;
axLiveX1.DefaultCam = 8;
axLiveX1.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX1_OnGetPicture);
axLiveX1.AutoLogin = true;
if (axLiveX1.Connect())
{
}
axLiveX1.StartGrapImage(true);
axLiveX2.IpAddress = ipAddress;
axLiveX2.UserName = username;
axLiveX2.Password = password;
axLiveX2.DataPort = 5550;
axLiveX2.CommandPort = 4550;
axLiveX2.AudioDataPort = 6550;
axLiveX2.DefaultCam = 8;
axLiveX2.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX2_OnGetPicture);
axLiveX2.AutoLogin = true;
axLiveX2.Connect();
axLiveX2.StartGrapImage(true);
}
else
{
axLiveX3.IpAddress = ipAddress;
axLiveX3.UserName = username;
axLiveX3.Password = password;
axLiveX3.DataPort = 5550;
axLiveX3.CommandPort = 4550;
axLiveX3.AudioDataPort = 6550;
axLiveX3.DefaultCam = 8;
axLiveX3.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX3_OnGetPicture);
axLiveX3.AutoLogin = true;
axLiveX3.Connect();
axLiveX3.StartGrapImage(true);
axLiveX4.IpAddress = ipAddress;
axLiveX4.UserName = username;
axLiveX4.Password = password;
axLiveX4.DataPort = 5550;
axLiveX4.CommandPort = 4550;
axLiveX4.AudioDataPort = 6550;
axLiveX4.DefaultCam = 8;
axLiveX4.OnGetPicture += new AxLIVEXLib._DLiveXEvents_OnGetPictureEventHandler(axLiveX4_OnGetPicture);
axLiveX4.AutoLogin = true;
axLiveX4.Connect();
axLiveX4.StartGrapImage(true);
}
}
Try something like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Col A", typeof(int));
dt.Columns.Add("Col B", typeof(int));
dt.Columns.Add("Col C", typeof(int));
dt.Rows.Add(new object[] { 1, 2, 3});
dt.Rows.Add(new object[] { 10, 20, 30 });
dt.Rows.Add(new object[] { 100, 200, 300 });
List<DataRow> rows = dt.AsEnumerable().Select(x => x).ToList();
var numbers = dt.AsEnumerable().Select(x => x.ItemArray).ToList();
}
}
}
You can get data of any cell like this with your original code
foreach (DataRow row in dt.Rows)
{
string colA = (string)row["Col A"];
}
To Get entire column try something like this
var colA = dt.AsEnumerable().Select(x => x.Field<string>("Col A")).ToList();