简体   繁体   English

xml导入到datagridview c#

[英]Xml Import to datagridview c#

Can you help me import this XML? 您能帮我导入这个XML吗?

My difficulty is that he has no Elements. 我的困难是他没有元素。

Ex: 例如:

<?xml version="1.0" encoding="Windows-1252"?>
<TBL>
  <CLI001>
    <NrCli>1000</NrCli>
    <Nome>Garagem Mira-Sintra, Lda.</Nome>
    <CPost>2710-011 SINTRA</CPost>
    <Comercial>7</Comercial>
    <VndNome>A. Tomás &amp; Lúcio- Terraplanagens e Cofragens, Lda</VndNome>
  </CLI001>
  <CLI002>
    <NrCli>1001</NrCli>
    <Nome>Auto Mecânica Torreense, Lda</Nome>
    <CPost>2560-231 TORRES VEDRAS</CPost>
    <Comercial>8</Comercial>
    <VndNome>Ricardo Rui Ribeiro - Sociedade de advogados</VndNome>
  </CLI002>
  <CLI003>
    <NrCli>1002</NrCli>
    <Nome>Auto Peças de Miranda, Lda</Nome>
    <CPost>5210-300 SÃO MARTINHO DE ANGUEIRA</CPost>
    <Comercial>10</Comercial>
    <VndNome>Jacinto Marques de Almeida Saraiva</VndNome>
  </CLI003>
<TBL>

Only the first record is import: 只有第一个记录是导入:

打印结果

try
{
  DataSet dataSet = new DataSet();
  dataSet.ReadXml(@"C:\Users\Rui\Desktop\myfilename.xml");
  dataGridView1.DataSource = dataSet.Tables[0];
}
catch (Exception ex)
{
  MessageBox.Show(ex.ToString());
}

I can not see a way to get around this: s 我看不到解决此问题的方法:s

Then end Tag <TBL> should be closing tag </TBL> . 然后,结束标签<TBL>应该是结束标签</TBL> Next time you can use this URL to validate your xml. 下次您可以使用 URL验证xml。

Firstly, there's a typo in your example xml, it should have a closing tag. 首先,示例xml中有一个错字,应该有一个结束标记。 I'm assuming that your actual XML has the closing tag, since your code would have failed when it tried to load the XML into the DataSet. 我假设您的实际XML具有结束标记,因为当您尝试将XML加载到DataSet中时,您的代码将失败。

The reason that you're only seeing one row in your datagridview is because there is only one row in dataset.Tables[0]. 那你只看到你的datagridview一排的原因是因为只有一个dataset.Tables [0]行。 Each of your CLI tags (CLI001, CLI002, CLI003) are loaded as seperate tables into your dataset. 您的每个CLI标记(CLI001,CLI002,CLI003)都作为单独的表加载到数据集中。 Look at the structure of the data loaded in your datagrid view, it conforms to the child items of CLI001. 查看在datagrid视图中加载的数据的结构,它符合CLI001的子项。 If you want to display all of them in a single DataGridView, you will need to merge them into a single datatable. 如果要将它们全部显示在单个DataGridView中,则需要将它们合并到单个数据表中。

DataSet dataSet = new DataSet();
dataSet.ReadXml(@"C:\Users\Rui\Desktop\myfilename.xml");

//merge all the tables into a single one
var dtMerged = dataSet.Tables[0].Copy();

for (int i = 1; i < dataSet.Tables.Count; i++)
{
    dtMerged.Merge(dataSet.Tables[i]);
}

//set the datasource using the merged datatable
dataGridView1.DataSource = dtMerged;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM