从数据表中写入xml文件,忽略带有空格的列

时间:2015-01-29 21:36:58

标签: c# .net xml datatable

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

我想忽略这些列,如果它们中没有任何数据,则不要将它们放在xml文件中

它现在正在生成的xml文件的示例

this is the current output

如果客户街道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);

1 个答案:

答案 0 :(得分:0)

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

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.");
            }