在一个XML文件中保存和加载两次DataTable并加载

时间:2019-05-10 08:20:02

标签: c# xml datatable load

我无法将2x数据表保存到1个xml文件中。

我正在使用c#.Net 4.6 +

{
 "IsNew": "0",
 "Title": "Industry",
 "View": "grid",
 "File": "",
 "Items": [
 {
    "IsNew": "0",
    "Title": "Industrial Products",
    "Image": "Industrial-Products.png",
    "View": "list",
    "Items": [ 
               {
                "IsNew": "0",
                "Title": "Offerings",
                "View": "detaillist",
                "Items": []
               },
               {
               "IsNew": "0",
               "Title": "Collateral",
               "View": "multidetaillist",
               "Items": [
                          {
                           "IsNew": "0",
                           "Title": "Flyers and Brochures",
                           "Subtitle": "",
                           "Items": [

                                    {
                                     "IsNew": "0",
                                      "Title": "Building Solutions",
                                      "View": "pdf",
                                       "File": "Building_Solutions.pdf",
                                       "Type": "1"
                                    },
                                    {
                                     "IsNew": "0",
                                      "Title": "Industrial Machinery",
                                    "View": "pdf",
                                    "File": "Industrial_Machinery.pdf",
                                     "Type": "1"
                                    }, 
                                   {
                                   "IsNew": "0",
                                    "Title": "abc",
                                   "Image": "abc",
                                   "View": "pdf",
                                   "File": "abc",
                                   "Type": "1"
                                 }

           ]
          }
        ]

      }
     ]
    }
  ] 
}

用于使用加载即时消息:

DataTable dt = (DataTable)dataGridView1.DataSource;
DataTable dt1 = (DataTable)dataGridView2.DataSource;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "XML|*.xml";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            try
            {
                dt.WriteXml(sfd.FileName);
                dt1.WriteXml(sfd.FileName);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
            }
        }

我想将dt和dt1保存到xml文件,然后按1个xml文件加载。

我该如何保存? 当我使用上面的代码时,dt1会覆盖dt。

2 个答案:

答案 0 :(得分:0)

例如,您可以使用XmlDocument类创建自定义XML 与TextWriter结合使用

    TextWriter writer = null;

                    try
                    {
                        XmlDocument doc = new XmlDocument();

                        //xml decleration
                        var xmlDecleration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");

                        doc.AppendChild(xmlDecleration);

                        //create the 
                        XmlElement rootElement = doc.CreateElement("datatableTopLevelElement");//, HierachyFileConstants.EXPORT_NAMESPACE);//the root element
                        XmlAttribute versionAttribute = doc.CreateAttribute("someVersionAttribute");
                        versionAttribute.Value = Version;//set the version number
                        rootElement.Attributes.Append(versionAttribute);

                        doc.AppendChild(rootElement);

    XmlElement dataObjectType = doc.CreateElement("FirstDataTable");//element name

    using (var ms = new MemoryStream())
                            {
                                var serializer = new XmlSerializer(dataType.GetType());//datatable type(if you know it)
                                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                                ns.Add("", "");
                                writer = new StreamWriter(ms);
                                serializer.Serialize(writer, dataType, ns);

                                //for some reason using xmlSettings with UTF-8 encoding creates an extra unecessary character

                                //remove first line of xml file
                                var xmlData = string.Join(Environment.NewLine, Encoding.UTF8.GetString(ms.ToArray())
                                    .Split(Environment.NewLine.ToCharArray())
                                    .Skip(1)
                                    .ToArray());

                                var xmlElement = GetElement(xmlData);

                                dataObjectType.AppendChild(dataObjectType.OwnerDocument.ImportNode(xmlElement, true));
                            }

//end of first datatable -- repeat from first datable method to add second datatable(
     }
                        }

                    }

                    //var tes
                    //return new XmlDocument().LoadXml(doc.OuterXml.Replace("xmlns=\"" + string.Empty + "\"",string.Empty));
                    var docToReturn = new XmlDocument();
                    docToReturn.LoadXml(doc.OuterXml.Replace("xmlns=\"" + string.Empty + 

    "\"", string.Empty));
                        return docToReturn;
    }


The GetElement method looks like this 

    private XmlElement GetElement(string xml)
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                doc.DocumentElement.Attributes.RemoveNamedItem("xmlns");
                //doc.DocumentElement.NamespaceURI
                return doc.DocumentElement;
            }

仅在添加第一个数据表后-添加第二个数据表以将其添加到xml中,或创建数据表的列表并执行foreach语句使其更简单

答案 1 :(得分:0)

正如我在评论中所说。 最好,最简单的方法是将数据表添加到数据集中。

数据集通过代码合并为1:

  DataTable dt = (DataTable)dataGridView1.DataSource;
  DataSet ds = new DataSet();
  DataSet ds1 = new DataSet();
  ds.Tables.Add(dt);
  ds1.Tables.Add(dt1);
                DataTable dt1 = (DataTable)dataGridView2.DataSource;
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "XML|*.xml";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        ds.Merge(ds1);
                        ds.WriteXml(sfd.FileName);
                        //dt1.WriteXml(sfd.FileName);
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine(ex);
                    }
                }

然后像这样加载它:

   OpenFileDialog sfd = new OpenFileDialog();
        sfd.Filter = "XML|*.xml";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            string file = sfd.FileName;
            try
            {

                dt.ReadXml(file);
                dt1.ReadXml(file);

            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex);
            }
        }