使用Loop的DataTable到XML

时间:2013-09-17 12:47:25

标签: c# asp.net xml linq

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

enter image description here

我想像这样转换类似的内容。

<?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))));

2 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分: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();
}