类别:程序开发
日期:2022-04-14 浏览:2290 评论:0
问题描述:C# DataTable 转XML的时候 列值为空,不显示该列标签?
比如:下面内容,无法显示IP_NO列
查询DataTable数据:
输出xml内容:
当时使用的DataTable转xml的类:
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Xml; using System.Xml.Serialization; namespace ConvenienceServices.Tools { public class DataTableToXML { /// <summary> /// DataTable转XML /// </summary> /// <param name="xmlDS"></param> /// <returns></returns> public static string ConvertDataTableToXML(DataTable xmlDS) { MemoryStream stream = null; XmlTextWriter writer = null; try { stream = new MemoryStream(); writer = new XmlTextWriter(stream, Encoding.UTF8); xmlDS.WriteXml(writer); int count = (int)stream.Length; byte[] arr = new byte[count]; stream.Seek(0, SeekOrigin.Begin); stream.Read(arr, 0, count); UTF8Encoding utf = new UTF8Encoding(); return "<root>" + utf.GetString(arr).Trim().ToString() + "</root>"; } catch { return "<?xml version=\"1.0\" encoding=\"UTF - 8\"?>" + String.Empty; } finally { if (writer != null) writer.Close(); } } /// <summary> /// XML转DataTable /// </summary> /// <param name="xmlData"></param> /// <returns></returns> public static DataSet ConvertXMLToDataSet(string xmlData) { StringReader stream = null; XmlTextReader reader = null; try { DataSet xmlDS = new DataSet(); stream = new StringReader(xmlData); reader = new XmlTextReader(stream); xmlDS.ReadXml(reader); return xmlDS; } catch (Exception ex) { string strTest = ex.Message; return null; } finally { if (reader != null) reader.Close(); } } public static string return_str(DataTable dataTable) { XmlDocument xmlDocument = new XmlDocument(); return xmlDocument.InnerXml; } public static string SerializeDataTableXml(DataTable dt) { StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); XmlSerializer serializer = new XmlSerializer(typeof(DataTable)); serializer.Serialize(writer, dt); writer.Close(); return sb.ToString(); } } }
无法解决以上问题。
解决方案:
第一种方案:
sql语句中添加判断:NVL() 函数 判断,给个空格值
第二种方案:
手动写一个生成xml文档的函数:
public static string DataTable2XML(DataTable dt) { string retVal = ""; StringBuilder jsonBuilder = new StringBuilder(); for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { jsonBuilder.Append(string.Format("<{0}>{1}</{0}>", dt.Columns[j].ColumnName, dt.Rows[i][j].ToString())); } } retVal = jsonBuilder.ToString(); return retVal; }
效果如下:
DataTable
通过手写函数转化之后
发表评论 / 取消回复