使用DataTable.WriteXML创建XML但使用其他元素?

时间:2016-06-22 20:30:41

标签: c# xml datatable

Example

您在左侧看到的是一个简单的DataTable.WriteXML()调用的结果。你在左边看到的是我需要匹配的预定模式。我从SQL数据库填充数据表(请忽略我目前不包括ItemType元素)。如何在树中创建更高的前几个元素,然后从数据表中编写XML?

编辑:另一个问题浮现在脑海中。为什么有一个名为Document Element的根元素,我如何控制被调用的内容或消除它?

编辑:这是我迄今为止的代码尝试。

XmlWriter writer;
XmlWriterSettings xwSettings = new XmlWriterSettings();

xwSettings.Encoding = Encoding.UTF8;
xwSettings.Indent = true;

writer = XmlWriter.Create("c:\\Armanino\\Exigo\\TestItems.xml", xwSettings);

writer.WriteStartElement("GreatPlainsIntegration");
writer.WriteStartElement("TransmissionDate");
writer.WriteString(string.Format("{0:yyyy-M-d}", DateTime.Now));
writer.WriteEndElement();

writer.WriteStartElement("Batch");
writer.WriteStartElement("BatchSource");
writer.WriteString("Inv Mstr");
writer.WriteEndElement();

dtItems.WriteXml(writer);

writer.WriteEndElement();

writer.Close();

导致此文件:

Test File 2

我尝试使用writer.WriteAttributeString()创建GreatPlainsIntegration元素的xmlns:integration部分,然而,它抱怨":"。

编辑:我的已实施解决方案:包括Batch元素的其他子元素和第二个Batch元素。

XDocument xd = XDocument.Parse(GetItemHeader());
XElement gpIntegration = (XElement)xd.FirstNode;

gpIntegration.Add(new object[] 
{
    new XElement("TransmissionDate", DateTime.Now.ToString("yyyy-M-d")), 
    new XElement("TransmissionTime", DateTime.Now.ToString("HH:mm")), 
    new XElement("Batch", new object[]
    {
        new XElement("TargetCatalog", dtItemsLWI.Rows[0].Field<string>(0)),
        new XElement("BatchSource", "Inv Mstr"),
        new XElement("BatchNumber", GetBatchName()), 
        new XElement("BatchComment", GetBatchComment())
    }), 
    new XElement("Batch", new object[]
    {
        new XElement("TargetCatalog", dtItemsLWE.Rows[0].Field<string>(0)),
        new XElement("BatchSource", "Inv Mstr"), 
        new XElement("BatchNumber", GetBatchName()),
        new XElement("BatchComment", GetBatchComment())
    })
});

XElement batchElementLWI = gpIntegration.Descendants("Batch").FirstOrDefault();
foreach (DataRow row in dtItemsLWI.Rows)
{
    batchElementLWI.Add(new XElement("Item", new XElement[]
    {
        new XElement(dtItemsLWI.Columns[1].ColumnName, row.Field<string>(1)), 
        new XElement(dtItemsLWI.Columns[2].ColumnName, row.Field<string>(2)),
        new XElement(dtItemsLWI.Columns[3].ColumnName, row.Field<string>(3)), 
        new XElement(dtItemsLWI.Columns[4].ColumnName, row.Field<string>(4))
    }));
}

DataTable dtItemSitesLWI = new DataTable();
dtItemSitesLWI.TableName = "ItemSite";

dtItemSitesLWI.Columns.Add("LegalEntityCode", typeof(string));
dtItemSitesLWI.Columns.Add("ItemNumber", typeof(string));
dtItemSitesLWI.Columns.Add("LocationCode", typeof(string));

da.GetItemSitesLWI(ref dtItemSitesLWI, sqlConn);

foreach (DataRow row in dtItemSitesLWI.Rows)
{
    batchElementLWI.Add(new XElement("ItemSite", new XElement[]
    {
        new XElement(dtItemSitesLWI.Columns[1].ColumnName, row.Field<string>(1)),
        new XElement(dtItemSitesLWI.Columns[2].ColumnName, row.Field<string>(2))
    }));
}

XElement batchElementLWE = gpIntegration.Descendants("Batch").Skip(1).FirstOrDefault();
foreach (DataRow row in dtItemsLWE.Rows)
{
    batchElementLWE.Add(new XElement("Item", new XElement[]
    {
        new XElement(dtItemsLWE.Columns[1].ColumnName, row.Field<string>(1)), 
        new XElement(dtItemsLWE.Columns[2].ColumnName, row.Field<string>(2)),
        new XElement(dtItemsLWE.Columns[3].ColumnName, row.Field<string>(3)), 
        new XElement(dtItemsLWE.Columns[4].ColumnName, row.Field<string>(4))
    }));
}

DataTable dtItemSitesLWE = new DataTable();
dtItemSitesLWE.TableName = "ItemSite";

dtItemSitesLWE.Columns.Add("LegalEntityCode", typeof(string));
dtItemSitesLWE.Columns.Add("ItemNumber", typeof(string));
dtItemSitesLWE.Columns.Add("LocationCode", typeof(string));

da.GetItemSitesLWE(ref dtItemSitesLWE, sqlConn);

foreach (DataRow row in dtItemSitesLWE.Rows)
{
    batchElementLWE.Add(new XElement("ItemSite", new XElement[]
    {
        new XElement(dtItemSitesLWE.Columns[1].ColumnName, row.Field<string>(1)),
        new XElement(dtItemSitesLWE.Columns[2].ColumnName, row.Field<string>(2))
    }));
}

XmlWriter writer;
XmlWriterSettings xwSettings = new XmlWriterSettings();

xwSettings.Encoding = Encoding.UTF8;
xwSettings.Indent = true;

writer = XmlWriter.Create("c:\\Armanino\\Exigo\\TestItems.xml", xwSettings);

xd.WriteTo(writer);

writer.Close();

2 个答案:

答案 0 :(得分:1)

您可以使用XmlWriter手动创建其他元素。但只能在DataSet / DataTable之前或之后。

var dt = new DataTable("Item");
dt.Columns.Add("ItemNumber");
dt.Columns.Add("ItemDescription");
dt.Columns.Add("ItemClass");

dt.Rows.Add("number1", "desc1", "class1");
dt.Rows.Add("number2", "desc2", "class2");
dt.Rows.Add("number3", "desc3", "class3");

var ds = new DataSet("Batch");
ds.Tables.Add(dt);



var settings = new XmlWriterSettings { Indent = true };

using (var writer = XmlWriter.Create("test.xml", settings))
{
    writer.WriteStartElement("GreatPlainsIntegration");

    writer.WriteElementString("TransmissionDate", "2015-5-6");
    writer.WriteElementString("TransmissionTime", "20:00");

    //writer.WriteElementString("TargetCatalog", "LWI");
    // and so on

    ds.WriteXml(writer);
}

您不需要命名空间。迪西。

也许您应该将TargetCatalogBatchSource和其他元素放在Batch元素之前,与Transmission*元素处于同一级别?在这种情况下,将XML中的数据读回DataSet将很容易。

使用DataSet允许将任意名称设置为DataTable而不是DocumentElement

答案 1 :(得分:1)

尝试XML Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Item> items = new List<Item>() {
                new Item() { itemNumber = "PHAN-PHN-001", itemDescription = "Standard Phone Package", itemClass = "RETAIL"},
                new Item() { itemNumber = "OM0325", itemDescription = "Dual Basic Headset", itemClass = "CATALOG"},
                new Item() { itemNumber = "OM01373", itemDescription = "Light Cordless 1", itemClass = "CATALOG"}
            };

            string header = "<?xml version=\"1.0\" encoding= \"utf-8\" ?>" +
                "<GreatPlainIntegration></GreatPlainIntegration>";

            XDocument doc = XDocument.Parse(header);
            XElement greatPlainsIntegration = (XElement)doc.FirstNode;

            greatPlainsIntegration.Add(new object[] {
                new XElement("TransmissionDate", DateTime.Now.ToString("yyyy-M-d")),
                new XElement("Batch", new object[] {
                    new XElement("BatchSource", "Inv Mstr"),
                    new XElement("DocumentElement")
                })
            });
            XElement documentElement = greatPlainsIntegration.Descendants("DocumentElement").FirstOrDefault();
            documentElement.Add(items.Select(x => new XElement("Item", new XElement[] {
                new XElement("ItemNumber", x.itemNumber),
                new XElement("ItemDescription", x.itemDescription),
                new XElement("ItemClass", x.itemClass)
            })).ToArray());

        }
    }
    public class Item
    {
        public string itemNumber { get; set; }
        public string itemDescription { get; set; }
        public string itemClass { get; set; }
    }
}