【问题标题】:write xml file from data table ignoring columns with white spaces从数据表中写入 xml 文件,忽略带空格的列
【发布时间】:2015-01-29 21:36:57
【问题描述】:

我正在尝试将数据表中的数据导出到 xml 文件中。我有这部分工作,但是当记录没有任何数据或空白时,它仍然将它写入 xml 文件中,并保留 XML:space。

如果它们中没有任何数据,我想忽略这些列并且不在 xml 文件中包含它们

现在生成的 xml 文件示例

如果客户街道 3 和 4 节点中没有任何值,我希望不打印它们。

这是我的代码

using System.IO;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.Xml;

namespace InvoicePrintProgram
{
   class XMLGenerator
   {
    //Defining method that generates  XMl Files
    public void Start(String XmlFilepath, string XMlFileName, DataTable DT, int PageCountOut, int SequenceCountOut, int[] PrefIndex/*, int[] SequenceIndex, IEnumerable<String> chunk, int IndexCount out int IndexCountOut*/)
    {
        // Creates Xml file from datatable using the wrtieXml method 

        FileStream streamWrite = new FileStream(XmlFilepath, System.IO.FileMode.Create);

        System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
        settings.Indent = true;
        //settings.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1") 
        settings.Encoding = System.Text.Encoding.UTF8;
        settings.CloseOutput = true;
        settings.CheckCharacters = true;
        settings.NewLineChars = "\r\n";

        DT.WriteXml(streamWrite, XmlWriteMode.IgnoreSchema);

【问题讨论】:

  • 不确定您发布的代码与问题的关系。您还介意清理样本,使其没有不相关的代码/空白吗?还请澄清检查值不为空的哪一部分会导致您出现问题。
  • 按要求清理了代码。我想看看如果记录列中没有数据,我是如何无法打印客户地址 3 和 4 的。
  • 现在看起来好多了 - 谢谢。我不认为你可以配置 DataTable 来做你想做的事,但我对这个类的经验很少 - 所以希望有办法。

标签: c# .net xml datatable


【解决方案1】:

您可以从该 DataTable 创建一个对象列表并使用以下内容:

List<string> xml_string = new List<string>();
xml_string.Add("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
xml_string.Add("anything you need as header");
foreach(string current_string in your_object_of_DataTable)
{


 if(current_string!=null || current_string.Trim()!="")
    {
      xml_string.Add("<Your Tag>"+current_string+"</Your Tag>");
    }
}
 try
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\xml_file_name.xml"))
                {
                    foreach (string line in xml_string)
                    {
                        file.WriteLine(line);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                MessageBox.Show("File exported.");
            }

【讨论】:

    猜你喜欢
    • 2019-04-02
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多