C# Serialization with repeating Nodes - c#

I have to serialize a class to achieve below format. Values that
appear in 'repeatnode' are fetched from DB. Could anyone help me
form a class serialize in to below xml. Also how the values can be
assigned to the repeating tags.
<ParentNode>
<docInfo>
<doc>name</doc>
<fileInfo>
<Date>2016-02-25T12:52:00</Date>
<software>Export</software>
<Creator>export</Creator>
</fileInfo>
</docInfo>
<repeatnode id="XXXXXXXXXXX" idval="XXXXXXXX" idsub="XXXX">
<name>XXXX</name>
<namebore>namebore</namebore>
</repeatnode>
<repeatnode id="XXXXXXXXXXX" idval="XXXXXXXX" idsub="XXXX">
<name>XXXX</name>
<namebore>namebore</namebore>
</repeatnode>
<repeatnode id="XXXXXXXXXXX" idval="XXXXXXXX" idsub="XXXX">
<name>XXXX</name>
<namebore>namebore</namebore>
</repeatnode>
</ParentNode>

Use a join query to the database to get the datatable below. Then use the code below to create the xml
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("DocName", typeof(string));
dt.Columns.Add("Date", typeof(DateTime));
dt.Columns.Add("software", typeof(string));
dt.Columns.Add("Creator", typeof(string));
dt.Columns.Add("nodeId", typeof(string));
dt.Columns.Add("idVal", typeof(string));
dt.Columns.Add("idSub", typeof(string));
dt.Columns.Add("nodeName", typeof(string));
dt.Columns.Add("namebore", typeof(string));
dt.Rows.Add(new object[] { "name", DateTime.Parse("2016-02-25T12:52:00"), "Export", "export", "XXXXXXXXXXX", "XXXXXXXX", "XXXX", "XXXX", "namebore" });
dt.Rows.Add(new object[] { "name", DateTime.Parse("2016-02-25T12:52:00"), "Export", "export", "XXXXXXXXXXX", "XXXXXXXX", "XXXX", "XXXX", "namebore" });
dt.Rows.Add(new object[] { "name", DateTime.Parse("2016-02-25T12:52:00"), "Export", "export", "XXXXXXXXXXX", "XXXXXXXX", "XXXX", "XXXX", "namebore" });
dataGridView1.DataSource = dt;
var groups = dt.AsEnumerable()
.GroupBy(x => new { doc = x.Field<string>("DocName"), date = x.Field<DateTime>("date"), software = x.Field<string>("software"), creator = x.Field<string>("Creator") }).ToList();
XElement parentNode = new XElement("ParentNode");
foreach (var group in groups)
{
XElement docInfo = new XElement("docInfo", new object[] {
new XElement("doc", group.Key.doc),
new XElement("fileinfo", new object[] {
new XElement("Date", group.Key.date.ToString("yyyy-MM-ddThh:mm:ss")),
new XElement("softwate", group.Key.software),
new XElement("Creator", group.Key.creator)
})
});
parentNode.Add(docInfo);
foreach (var row in group)
{
XElement repeatnode = new XElement("repeatnode", new object[] {
new XAttribute("id", row.Field<string>("nodeId")),
new XAttribute("idval", row.Field<string>("idVal")),
new XAttribute("idsub", row.Field<string>("idSub")),
new XElement("name", row.Field<string>("nodeName")),
new XElement("namebore", row.Field<string>("namebore"))
});
parentNode.Add(repeatnode);
}
}
}
}
}

Related

How to read multiple node element from xml data in c#

I have xml like below. Here allowedSessionType can be multiple value sometime. Could anyone help me to read both and store it into data table c# gridview.
I tried but getting single value
<sessionManagementSubscriptionData>
<singleNssai>1-000001</singleNssai>
<dnnConfiguration>
<pduSessionTypes>
<defaultSessionType>IPV4</defaultSessionType>
<allowedSessionType>IPV4</allowedSessionType>
</pduSessionTypes>
<sscModes>
<defaultSscMode>SSC_MODE_1</defaultSscMode>
<allowedSscMode>SSC_MODE_1</allowedSscMode>
</sscModes>
</dnnConfiguration>
<dnnConfiguration>
<pduSessionTypes>
<defaultSessionType>IPV4</defaultSessionType>
<allowedSessionType>IPV4</allowedSessionType>
<allowedSessionType>IPV6</allowedSessionType>
</pduSessionTypes>
<sscModes>
<defaultSscMode>SSC_MODE_1</defaultSscMode>
<allowedSscMode>SSC_MODE_1</allowedSscMode>
</sscModes>
</dnnConfiguration>
</sessionManagementSubscriptionData>
DataTable dt1 = new DataTable();
dt1.Columns.Add("Allowed Session Type", typeof(string));
XmlNodeList nodeList1 = doc.SelectNodes("//sessionManagementSubscriptionData/dnnConfiguration");
foreach (XmlNode node1 in nodeList1)
{
DataRow dtrow1 = dt1.NewRow();
var SMSDDefaultSessionType = node1.SelectSingleNode("//defaultSessionType").InnerText;
dtrow1["Default Session Type"] = SMSDDefaultSessionType;
var SMSDallowedSessionType = node1.SelectSingleNode("//allowedSessionType").InnerText;
dtrow1["Allowed Session Type"] = SMSDallowedSessionType;
dt1.Rows.Add(dtrow1);
}
GridView2.DataSource = dt1;
GridView2.DataBind();
using System.Xml.Serialization;
XmlSerializer serializer = new XmlSerializer(typeof(SessionManagementSubscriptionData));
using (StringReader reader = new StringReader(xml))
{
var test = (SessionManagementSubscriptionData)serializer.Deserialize(reader);
//test.DnnConfiguration has your data
}
[XmlRoot(ElementName="pduSessionTypes")]
public class PduSessionTypes {
[XmlElement(ElementName="allowedSessionType")]
public List<string> AllowedSessionType;
}
[XmlRoot(ElementName="sscModes")]
public class SscModes {
[XmlElement(ElementName="defaultSscMode")]
public string DefaultSscMode;
[XmlElement(ElementName="allowedSscMode")]
public string AllowedSscMode;
}
[XmlRoot(ElementName="dnnConfiguration")]
public class DnnConfiguration {
[XmlElement(ElementName="pduSessionTypes")]
public PduSessionTypes PduSessionTypes;
[XmlElement(ElementName="sscModes")]
public SscModes SscModes;
}
[XmlRoot(ElementName="sessionManagementSubscriptionData")]
public class SessionManagementSubscriptionData {
[XmlElement(ElementName="singleNssai")]
public DateTime SingleNssai;
[XmlElement(ElementName="dnnConfiguration")]
public List<DnnConfiguration> DnnConfiguration;
}
Use this webiste to convert xml to c#
Here is results in a DataTable using Xml Linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication11
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Default Session Type", typeof(string));
dt.Columns.Add("Allowed Session Type", typeof(string));
dt.Columns.Add("Default SSC Mode", typeof(string));
dt.Columns.Add("Allowed SSC Mode", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement dnnConfiguration in doc.Descendants("dnnConfiguration"))
{
string defaultSessionType = (string)dnnConfiguration.Descendants("defaultSessionType").FirstOrDefault();
string[] allowedSessionType = dnnConfiguration.Descendants("allowedSessionType").Select(x => (string)x).ToArray();
string defaultSscMode = (string)dnnConfiguration.Descendants("defaultSscMode").FirstOrDefault();
string[] allowedSscMode = dnnConfiguration.Descendants("allowedSscMode").Select(x => (string)x).ToArray();
dt.Rows.Add(new object[] { defaultSessionType, string.Join(",", allowedSessionType), defaultSscMode, string.Join(",", allowedSscMode) });
}
}
}
}

C# need to store a parsed version of SQL Server table, use datatable or list

I'm new to C#. I know that datatable is very efficient for reading an entire SQL table and outputting data to griddataview. However I need to do some parsing before storing the data in my griddataview. I was thinking reading the table row by row and grouping the data when applicable. Would a datatable or a list be more applicable in my case?
ORIGINAL TABLE PARSED TABLE I need to pass to datagridview
Name Workdate Name M T W TH F SAT SUN
Nicole WED Nicole Y Y Y
Nicole THR Jason Y
Nicole MON
Jason Tue
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> dict = new Dictionary<string, string>() {
{"MON", "M"},{"TUE", "T"},{"WED", "W"},{"THR", "TH"},{"FRI", "F"},{"SAT", "SAT"},{"SUN", "SUN"}};
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Workdate", typeof(string));
dt.Rows.Add(new object[] { "Nicole", "WED" });
dt.Rows.Add(new object[] { "Nicole", "THR" });
dt.Rows.Add(new object[] { "Nicole", "MON" });
dt.Rows.Add(new object[] { "Jason", "TUE" });
DataTable pivot = new DataTable();
pivot.Columns.Add("Name",typeof(string));
DataColumn[] columns = dict.Select(x => new DataColumn(x.Value, typeof(string))).ToArray();
pivot.Columns.AddRange(columns);
var people = dt.AsEnumerable().GroupBy(x => x.Field<string>("Name")).ToArray();
foreach (var person in people)
{
DataRow pivotRow = pivot.Rows.Add();
pivotRow["Name"] = person.Key;
foreach (DataRow row in person)
{
string day = row.Field<string>("Workdate");
pivotRow[dict[day]] = "Y";
}
}
}
}
}

How to Display data horizontally

I have four tables (employees, allowances,deductions and Ajenda these are main tables , when i save employees financial details i save them in a different tables as image .
I want to display the employees detail and financial details in a horizontally way .
I'm using C# and SQLServer 2012 .
first table contains employees main details , second contain employees id with there allowances and other tables .
My tables
Here is my code before somebody closes it again. I decided not to use group since there would be a lot of left outer joins which would complicate solution. Decided just to create a table and then add the data directly to the results table.
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 employees = new DataTable();
employees.Columns.Add("empID", typeof(int));
employees.Columns.Add("emp_name", typeof(string));
employees.Columns.Add("emp_tele", typeof(string));
employees.Rows.Add(new object[] { 1, "David", "025896325" });
employees.Rows.Add(new object[] { 2, "John", "856985658" });
employees.Rows.Add(new object[] { 3, "Micheal", "654687887" });
DataTable allowances = new DataTable();
allowances.Columns.Add("empID", typeof(int));
allowances.Columns.Add("allow_name", typeof(string));
allowances.Columns.Add("allow_Amount", typeof(int));
allowances.Rows.Add(new object[] { 1, "allow1", 100 });
allowances.Rows.Add(new object[] { 1, "allow2", 200 });
allowances.Rows.Add(new object[] { 1, "allow3", 300 });
allowances.Rows.Add(new object[] { 2, "allow1", 100 });
allowances.Rows.Add(new object[] { 2, "allow2", 200 });
DataTable deductions = new DataTable();
deductions.Columns.Add("empID", typeof(int));
deductions.Columns.Add("Dedu_name", typeof(string));
deductions.Columns.Add("Dedu_Amount", typeof(int));
deductions.Rows.Add(new object[] { 1, "ded1", 10 });
deductions.Rows.Add(new object[] { 1, "ded2", 5 });
deductions.Rows.Add(new object[] { 2, "ded1", 10 });
DataTable ajenda = new DataTable();
ajenda.Columns.Add("empID", typeof(int));
ajenda.Columns.Add("ajenda_name", typeof(string));
ajenda.Columns.Add("ajenda_Amount", typeof(int));
ajenda.Rows.Add(new object[] { 1, "aj1", 200 });
ajenda.Rows.Add(new object[] { 1, "aj1", 200 });
ajenda.Rows.Add(new object[] { 1, "aj2", 300 });
DataTable results = employees.Clone();
string[] allow_names = allowances.AsEnumerable().Select(x => x.Field<string>("allow_name")).Distinct().OrderBy(x => x).ToArray();
foreach (string name in allow_names)
{
results.Columns.Add(name, typeof(string));
}
string[] dedu_names = deductions.AsEnumerable().Select(x => x.Field<string>("Dedu_name")).Distinct().OrderBy(x => x).ToArray();
foreach (string name in dedu_names)
{
results.Columns.Add(name, typeof(string));
}
string[] ajenda_names = ajenda.AsEnumerable().Select(x => x.Field<string>("ajenda_name")).Distinct().OrderBy(x => x).ToArray();
foreach (string name in ajenda_names)
{
results.Columns.Add(name, typeof(string));
}
//add employees to result table
foreach(DataRow row in employees.AsEnumerable())
{
results.Rows.Add(row.ItemArray);
}
var groupAllownaces = allowances.AsEnumerable().GroupBy(x => x.Field<int>("empID"));
foreach (var group in groupAllownaces)
{
DataRow employeeRow = results.AsEnumerable().Where(x => x.Field<int>("empID") == group.Key).First();
foreach (DataRow row in group)
{
employeeRow[row.Field<string>("allow_name")] = row.Field<int>("allow_Amount");
}
}
var groupDeductions = deductions.AsEnumerable().GroupBy(x => x.Field<int>("empID"));
foreach (var group in groupDeductions)
{
DataRow employeeRow = results.AsEnumerable().Where(x => x.Field<int>("empID") == group.Key).First();
foreach (DataRow row in group)
{
employeeRow[row.Field<string>("Dedu_name")] = row.Field<int>("Dedu_Amount");
}
}
var groupAjenda = ajenda.AsEnumerable().GroupBy(x => x.Field<int>("empID"));
foreach (var group in groupAjenda)
{
DataRow employeeRow = results.AsEnumerable().Where(x => x.Field<int>("empID") == group.Key).First();
foreach (DataRow row in group)
{
employeeRow[row.Field<string>("ajenda_name")] = row.Field<int>("ajenda_Amount");
}
}
}
}
}

hierarchical treeview in c# Winforms with continent, nation, city

I have a SQL table:
REGION NATION CITY
Europe Austria Wien
Europe Austria Graz
APA Australia Sidney
Etc...etc...
Basically, region, nation, and city.
I would like to build a hierarchical Treeview like:
-EUROPE
--Austria
---Graz
---Wien
-APA
--Australia
---Sydney
I used Datatable to get data from a database.
Someone can help me with the cycle FOR and various nested if to accomplish that?
Many thanks in advance
Try following :
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 WindowsFormsApplication51
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
try
{
DataTable dt = new DataTable();
dt.Columns.Add("REGION", typeof(string));
dt.Columns.Add("NATION", typeof(string));
dt.Columns.Add("CITY", typeof(string));
dt.Rows.Add(new object[] { "Europe", "Austria", "Wien" });
dt.Rows.Add(new object[] { "Europe", "Austria", "Graz" });
dt.Rows.Add(new object[] { "APA", "Australia", "Sidney" });
foreach (var region in dt.AsEnumerable().GroupBy(x => x.Field<string>("REGION")))
{
TreeNode regionNode = new TreeNode(region.Key);
treeView1.Nodes.Add(regionNode);
foreach (var nation in region.GroupBy(x => x.Field<string>("NATION")))
{
TreeNode nationNode = new TreeNode(nation.Key);
regionNode.Nodes.Add(nationNode);
foreach (string city in nation.Select(x => x.Field<string>("CITY")))
{
TreeNode cityNode = new TreeNode(city);
nationNode.Nodes.Add(cityNode);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
treeView1.ExpandAll();
}
}
}

C# dataGridView from XML file

I know there are lots of resources that show how to bind dataGridViews to XML files or populate from XML, but the XML i'm using as source is a bit more complex than any example I've seen used and I'm struggling. (although it really shouldn't be difficult)
I basically need to run several queries (I think) to get the data I want to populate the DGV, because the elements I want the content from are on different parent nodes of the XML.
Here is what I have, and the comments should show you what I'm trying to achieve:
XDocument xmlDoc = XDocument.Load("Techdocx_dml.xml");
var q = from c in xmlDoc.Root.Descendants("dmentry")
.Descendants("avee")
//.Descendants("dmtitle") I also need to access this descendant
select new
{
modelic = c.Element("modelic").Value,
sdc = c.Element("sdc").Value,
chapnum = c.Element("chapnum").Value,
section = c.Element("section").Value,
subsect = c.Element("subsect").Value,
subject = c.Element("subject").Value,
discode = c.Element("discode").Value,
discodev = c.Element("discodev").Value,
incode = c.Element("incode").Value,
incodev = c.Element("incodev").Value,
itemloc = c.Element("itemloc").Value,
// techname = c.Element("techname").Value,
//need this value, which is on the "dmtitle" node, not the "avee" node
};
dataGridView1.DataSource = q.ToList();
dataGridView1.ColumnHeadersVisible = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
This is what i want in my dataGridView:
AA A 32 3 5 00 01 A 018 A A | Some title 1 | Introduction
AA A 32 3 5 00 01 A 920 A A | Some title 2 | Some infoname 2
How do I achieve this please? Example XML below:
<dml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dmentry>
<addresdm>
<dmc>
<avee>
<modelic>AA</modelic>
<sdc>A</sdc>
<chapnum>32</chapnum>
<section>3</section>
<subsect>5</subsect>
<subject>00</subject>
<discode>01</discode>
<discodev>A</discodev>
<incode>018</incode>
<incodev>A</incodev>
<itemloc>A</itemloc>
</avee>
</dmc>
<dmtitle>
<techname>Some title 1</techname>
<infoname>Introduction</infoname>
</dmtitle>
<issno issno="001" type="New"/>
<issdate year="2016" month="06" day="10"/>
<language language="SX" country="GB"/>
</addresdm>
<security class="1"/>
</dmentry>
<dmentry>
<addresdm>
<dmc>
<avee>
<modelic>AA</modelic>
<sdc>A</sdc>
<chapnum>32</chapnum>
<section>3</section>
<subsect>5</subsect>
<subject>00</subject>
<discode>01</discode>
<discodev>A</discodev>
<incode>920</incode>
<incodev>A</incodev>
<itemloc>A</itemloc>
</avee>
</dmc>
<dmtitle>
<techname>Some title 2</techname>
<infoname>Some infoname 2</infoname>
</dmtitle>
<issno issno="001" type="New"/>
<issdate year="2016" month="06" day="10"/>
<language language="SX" country="GB"/>
</addresdm>
<security class="1"/>
</dmentry>
</dml>
Try this :
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;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
const string FILENAME = #"c:\temp\test.xml";
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("modelic", typeof(string));
dt.Columns.Add("sdc", typeof(string));
dt.Columns.Add("chapnum", typeof(string));
dt.Columns.Add("section", typeof(string));
dt.Columns.Add("subsect", typeof(string));
dt.Columns.Add("subject", typeof(string));
dt.Columns.Add("discode", typeof(string));
dt.Columns.Add("discodev", typeof(string));
dt.Columns.Add("incode", typeof(string));
dt.Columns.Add("incodev", typeof(string));
dt.Columns.Add("itemloc", typeof(string));
dt.Columns.Add("techname", typeof(string));
dt.Columns.Add("infoname", typeof(string));
XDocument doc = XDocument.Load(FILENAME);
foreach (XElement addresdm in doc.Descendants().Where(x => x.Name.LocalName == "addresdm"))
{
XElement avee = addresdm.Descendants("avee").FirstOrDefault();
XElement dmtitle = addresdm.Descendants("dmtitle").FirstOrDefault();
dt.Rows.Add(new object[] {
(string)avee.Element("modelic"),
(string)avee.Element("sdc"),
(string)avee.Element("chapnum"),
(string)avee.Element("section"),
(string)avee.Element("subsect"),
(string)avee.Element("subject"),
(string)avee.Element("discode"),
(string)avee.Element("discodev"),
(string)avee.Element("incode"),
(string)avee.Element("incodev"),
(string)avee.Element("itemloc"),
(string)dmtitle.Element("techname"),
(string)dmtitle.Element("infoname")
});
}
dataGridView1.DataSource = dt;
}
}
}

Categories