I've got a data table like
Now I have to get the value of the first two rows, and column 1 has the name of the element, and column 2 has the value of the element in xml using c# linq
after that,skip to 4th row and from 4th row to n rows,i want all values dynamically passed into element (element name i will hard code it)
note: Element means xml element required output: file.xml
//this My datatable ---- for datatable check the above image
//Result is my dataset which i got from my xlsx file and i converted dataset to datatable.
DataTable dt = result.Tables[0]; //Table[0] -- is my 1st sheet of xlsx file
var rows = dt.AsEnumerable().Take(2); //Taking first 2 rows
XElement xml1 = new XElement("ROOT",
from r in rows
select (
new XElement(r.Field<string>("Column0"),r.Field<object>("Column1"))
)
);
//Field<object>--object is datatype which takes anytype of value from columns or rows in data table
var n = result.Tables[0].Rows.Count;
var Ref = dt.AsEnumerable().Skip(3).Take(n-3);
XElement xml2 = new XElement("ROOT",
from rs in Ref
select (
new XElement("References",
new XElement("A", rs.Field<string>("Column0")),
new XElement("B", rs.Field<string>("Column1")),
new XElement("C", rs.Field<string>("Column2"))));
//Now merge those two xmls
var x1 = XDocument.Parse(xml1.ToString());
var x2 = XDocument.Parse(xml2.ToString());
x1.Root.Add(x2.Root.Elements());
x1.Save(@"D:\filename.xml");
For output check my question...
For your question, you want to get column value from specific rows and convert to xml file
by linq.
You could try the following code to get it.
var result1 = table.AsEnumerable().Take(2);
var result2 = table.AsEnumerable().Skip(3).Take(table.Rows.Count - 3);
XmlTextWriter writer = new XmlTextWriter("product.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.WriteStartElement("DFS");
foreach (DataRow item in result1)
{
createNode(item[0].ToString(), item[1].ToString(), writer);
}
foreach (DataRow item in result2)
{
writer.WriteStartElement("References");
createNode("A", item[0].ToString(), writer);
createNode("B", item[1].ToString(), writer);
createNode("C", item[2].ToString(), writer);
createNode("D", item[3].ToString(), writer);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.