0

我想将我的数据表转换为 XML。我有两个类似的数据表。

在此处输入图像描述

我想像这样转换类似的。

<?xml version="1.0" encoding="utf-8"?>
<root>
  <member>
    <refid>1</refid>
    <fname>Indocin</fname>
    <lname>David</lname>
    <activities>
      <refid>1</refid>
      <act>Swimming</act>
    </activities>
  <activities>
      <refid>1</refid>
      <act>running</act>
    </activities>
    <Date>2013-09-17T18:10:01.3452408+05:30</Date>
  </member>
  <member>
    <refid>2</refid>
    <fname>Indocin</fname>
    <lname>David</lname>
    <activities>
      <refid>2</refid>
      <act>playing</act>
    </activities>
    <activities>
      <refid>2</refid>
      <act>running</act>
    </activities>
   <activities>
      <refid>2</refid>
      <act>swimming</act>
    </activities>
    <Date>2013-09-17T18:10:01.3452408+05:30</Date>
  </member>
</root>

我在下面尝试过,但我需要通过循环使用数据表选择语句来执行此操作以进行 refid。谁能帮我解决这个问题。

 XDocument doc = new XDocument(new XElement("root",
                                             new XElement("member",
                                                 new XElement("refid", 1),
                                                 new XElement("fname", "Indocin"),
                                                 new XElement("lname", "David"),
                                                 new XElement("activities", new XElement("refid",1),
                                                     new XElement("act","Swimming")),
                                                 new XElement("Date", DateTime.Now))));
4

2 回答 2

1

我希望它会帮助你

private string CreateXML(DataTable table1, DataTable table2)
    {
        System.Text.StringBuilder sp = new System.Text.StringBuilder();

        sp.Append("<root>");
        for (int i = 0; i < table1.Rows.Count; i++)
        {

            sp.Append("<member>");
            sp.Append("<refid>" + table1.Rows[i]["refid"] + "</refid>");
            sp.Append("<fname>" + table1.Rows[i]["fname"] + "</fname>");
            sp.Append("<lname>" + table1.Rows[i]["lname"] + "</lname>");

            for (int j = 0; j < table2.Rows.Count; j++)
            {
                if (table1.Rows[i]["refid"] == table2.Rows[j]["refid"])
                {
                    sp.Append("<activities>");
                    sp.Append("<refid>" + table2.Rows[j]["refid"] + "</refid>");
                    sp.Append("<act>" + table2.Rows[j]["act"] + "</act>");

                    sp.Append("</activities>");
                }
            }

            sp.Append("<Date>" + table1.Rows[i]["Date"] + "</Date>");
            sp.Append("</member>");
        }

        sp.Append("</root>");
        return sp.ToString();
    }
于 2013-09-17T13:12:29.067 回答
0

您可以使用writeXML方法将其保存为XML这是有用的链接http://msdn.microsoft.com/en-us/library/system.data.datatable.writexml.aspx

string result;
using (StringWriter sw = new StringWriter()) {
dataTable.WriteXml(sw);
result = sw.ToString();
}
于 2013-09-17T12:51:09.537 回答