Leandro Machado Leandro Machado - 1 year ago 214
C# Question

XML editor in C# - now showing fields

I have a problem.

I have one XML file that have datafields that I want to read in a datagridview.


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DATAPACKET Version="2.0">
<FIELD attrname="ALMO_Exercicio" fieldtype="string" WIDTH="4"/>
<FIELD attrname="ALMO_MesReferencia" fieldtype="string" WIDTH="2"/>
<FIELD attrname="ALMO_Saldo" fieldtype="string" WIDTH="17"/>
<ROW ALMO_Exercicio="2016" ALMO_MesReferencia="01" ALMO_Saldo="0.00"/>

The C# file that read this:

XmlReader xmlFile = XmlReader.Create(ofd.FileName, new XmlReaderSettings());
dataGridView1.DataSource = ds.Tables[0].DefaultView;

So, the only thing that show when I open is:
software only shows the version of xml file

What I need to do?

Answer Source

You're going to have to process the XML yourself, you can't just load this into a DataSet as-is.

You can create columns from each FIELD and then get the row data by finding the attributes of the same names from each ROW. This is pretty trivial with LINQ to XML:

var doc = XDocument.Load(ofd.FileName);

var columns = doc.Descendants("FIELD")
    .Select(fieldName => new DataColumn(fieldName.Value))

var rows = doc.Descendants("ROW")
    .Select(row => columns.Select(col => (string)row.Attribute(col.ColumnName)).ToArray());

You can then create a DataTable from this:

var table = new DataTable();


foreach (var row in rows)

See this fiddle for a working demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download