【问题标题】:C# XML fail importingC# XML 导入失败
【发布时间】:2018-05-29 12:41:35
【问题描述】:

我正在尝试将 xml 文件导入 c# 数据网格视图。但是,每当我使用 .SelectNodes 时,都不会将任何标签读入我的 xmlnodelist。每当我对代码运行调试并在到达第一个 foreach 语句时单步执行代码时,它会立即离开该语句,我假设因为 xmlnodelist 内没有任何内容。这就是我到目前为止所拥有的。请帮忙。提前致谢

namespace DesktopApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int currRow = 0,currCell =0;
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string fileType = ofd.FileName;
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(fileType);
                XmlNode root = xDoc.DocumentElement;

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xDoc.NameTable);
                nsmgr.AddNamespace("df", "http://www.w3.org/2001/XMLSchema-instance");
                nsmgr.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");


                XmlNodeList listOfEmployees = root.SelectNodes("descendant::Employee",nsmgr);

                foreach (XmlNode employee in listOfEmployees)
                {
                    foreach (XmlNode characteristic in employee)
                    {
                        if (characteristic.InnerText != null)
                        {
                            dataGridView1.Rows[currRow].Cells[currCell].Value = characteristic.InnerText;
                        }
                        currRow++;
                        currCell++;
                    }

                }
            }
        }
    }
}

XML:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
    <ImportEmployees xmlns="http://m3as.com/SPDS" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <siteCode>AMH929</siteCode>
        <employees>
            <Employee>
                <EmployeeCode>10444</EmployeeCode>
                <HomeHourlyRate>11</HomeHourlyRate>
                <FirstName>John|Doe</FirstName>
                <LastName />
                <MiddleInitial />
                <Gender>M</Gender>
                <DateOfBirth>20000318</DateOfBirth>
                <ClockNo>10444</ClockNo>
                <DateOfHire>20150318</DateOfHire>
                <EffectiveDate>20160218</EffectiveDate>
                <Address>0000 W MAGNOLIA STREET</Address>
                <Address2 />
                <City>VALDOSTA</City>
                <State>GA</State>
                <Country />
                <PostalCode>12345</PostalCode>
                <EmployeeStatus>A</EmployeeStatus>
                <EmployeeType>Regular</EmployeeType>
                <FullTimePartTime>FT</FullTimePartTime>
                <HrlySlryNonExemptFluc1>Hourly</HrlySlryNonExemptFluc1>
                <PayGroup>0101</PayGroup>
                <ReviewDate />
                <PhoneNumber>1234567890</PhoneNumber>

            </Employee>
        </employees>
    </ImportEmployees>
</s:Body>

【问题讨论】:

  • 我没有收到错误,因为构建完成,问题是当我尝试导入 xml 文件时它什么都不导入
  • 我在尝试将其转换为 c# 类对象时在您的 XML 中遇到错误。

标签: c# xml


【解决方案1】:

您的命名空间声明看起来有点奇怪。这个对我有用:

var nsmgr = new XmlNamespaceManager(xDoc.NameTable);
nsmgr.AddNamespace("spds", "http://m3as.com/SPDS");

var listOfEmployees = root.SelectNodes("//spds:Employee", nsmgr);

【讨论】:

  • 感谢这项工作!我对导入 xml 文件有点陌生。我只是根据我从一些文件中看到的。
【解决方案2】:

在加载 DGV 之前尝试 xml linq 并将数据放入 DataTable 中

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 WindowsFormsApplication18
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Click += new EventHandler(openToolStripMenuItem_Click);
        }
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Text", typeof(string));

            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string fileType = ofd.FileName;
                XDocument xDoc = XDocument.Load(fileType);

                Boolean first = true;
                foreach (XElement employee in xDoc.Descendants().Where(x => x.Name.LocalName == "Employee"))
                {
                    if (first)
                    {
                        foreach (XElement characteristic in employee.Elements())
                        {
                            dt.Columns.Add(characteristic.Name.LocalName, typeof(string));
                        }
                        first = false;
                    }
                    dt.Rows.Add(employee.Elements().Select(x => (string)x).ToArray());

                }
                dataGridView1.DataSource = dt;
            }
        }
    }
}

【讨论】:

  • 我尝试以这种方式导入,但在导入后,除了第一个数据列之外,没有填充任何数据列,第一个数据列只显示“System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement ,System.String]"
  • 我在发布后进行了一些小更新。您缺少这些更新,尤其是 ToArray()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 2016-11-12
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多