比如我得出如下数据表id   pid   name
1    null  a
2    1     a1
3    null  b
4    3     b1
5    4     b11
6    3     b2
....
能否得出如下格式的XML?
<item id='1' text='a'>
   <item id='2' text='a1'></item>
</item>
<item id='3' text='b'>
   <item id='4' text='b1'>
        <item id='5' text='b11'></item>
   </item>
   <item id='6' text='b2'></item>
</item>
....请各位大侠帮帮忙,谢谢

解决方案 »

  1.   

    最简单的方式,
    先确定有几层关系,如果最多不超过3或4关系,那么可以
    先查询出pid为NULL的数据放在一个DATATABLE或者LIST里面,SELECT * FROM table where pid is null; 组成一级节点然后,循环从DATATABLE或者LIST里面取每条记录,执行SELECT * FROM table where pid=每行的Id,把查询到的数据依次插入到一级节点的子节点中。。后面依次类推。
      

  2.   

    把表中的数据导出为XML文件吗?
    关注下
      

  3.   

    可以不用,就拼凑成XML字符串就可以了
      

  4.   

    先把数据读出了,然后写XML。
    给你一个例子参考..
    StreamWriter sw1 = new StreamWriter(strFile);
                string[] arr = keyValue.Substring(0,keyValue.Trim().Length-1).Split(',');
                sw1.Write("<?xml version='1.0' encoding='UTF-8'?>");
                sw1.Write("<PaperInfoFile Version='2.0'>");
                sw1.Write("<KeyWords>");
                foreach (string sKey in arr)
                {
                    sw1.Write("<KeyWord>" + sKey + "</KeyWord>");
                }
                sw1.Write("</KeyWords>");
                sw1.Write("<PageList Date='" + dateStr + "' PaperName='解放报社数字剪报'>");
                int page = 0;
                DataSet dat = new DataSet();
                DataSet imaDat = new DataSet();
                #region 循环体
                for (int i = 1; i < contentID.Length; i++)
                {
                    if (contentID[i] != 0)
                    {
                        page++;                    string con1 = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
                        using (SqlConnection con = new SqlConnection(con1))
                        {
                            con.Open();
                            SqlCommand sqlCom = new SqlCommand("p_setXml", con);
                            sqlCom.Parameters.Add(new SqlParameter("@iAutoID", contentID[i]));
                            sqlCom.CommandType = CommandType.StoredProcedure;
                            SqlDataAdapter sqlD = new SqlDataAdapter(sqlCom);
                            sqlD.Fill(dat);                        SqlCommand sqlIma = new SqlCommand("p_setImageList", con);
                            sqlIma.Parameters.Add(new SqlParameter("@iNewsId", contentID[i]));
                            sqlIma.CommandType = CommandType.StoredProcedure;
                            SqlDataAdapter sqlDIma = new SqlDataAdapter(sqlIma);
                            sqlDIma.Fill(imaDat);
                        }
                        string swXmlPath = str + @"TempXml\" + "page_00" + page + tick + ".xml";//page_001190164446937.xml
                        strXmlPath.Add(swXmlPath);
                        StreamWriter sw = new StreamWriter(swXmlPath);
                        sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                        sw.WriteLine("<PageInfoFile Version='2.0'>");
                        //Height高度,PageName版名,PageNo版号,Width宽度
                        sw.WriteLine("<PageInfo PaperName='"+dat.Tables[0].Rows[0]["sSiteChinaName"]+"' Date='" +DateTime.Parse(dat.Tables[0].Rows[0]["dRalTime"].ToString().Split('.')[0]).ToString("yyyyMMdd")+ "' Height='" + dat.Tables[0].Rows[0]["iPageHeight"] + "' PageName='" + dat.Tables[0].Rows[0]["PageName"] + "' PageNo='" + dat.Tables[0].Rows[0]["sPageName"] + "' Width='" + dat.Tables[0].Rows[0]["iPageWidth"] + "'/>");
                        sw.WriteLine("<ArticleList>");
                        sw.WriteLine("<Article>");
                        //引题
                        sw.WriteLine("<IntroTitle><![CDATA[" + dat.Tables[0].Rows[0]["sIntroTitle"].ToString() + "]]></IntroTitle>");
                        //标题
                        sw.WriteLine("<Title><![CDATA[" + dat.Tables[0].Rows[0]["sNewsTitle"].ToString() + "]]></Title>");
                        //栏目
                        sw.WriteLine("<SubTitle><![CDATA[" + dat.Tables[0].Rows[0]["sSubTitle"].ToString() + "]]></SubTitle>");
                        //作者
                        sw.WriteLine("<Author>" + dat.Tables[0].Rows[0]["sAuther"].ToString() + "</Author>");
                        //报名
                        sw.WriteLine("<Source>" + dat.Tables[0].Rows[0]["sSiteChinaName"].ToString() + "</Source>");
                        //正文
                        sw.WriteLine("<Content><![CDATA[" + dat.Tables[0].Rows[0]["tContent"].ToString() + "]]></Content>");
                        DateTime DralDate = DateTime.Parse(dat.Tables[0].Rows[0]["dRalTime"].ToString());
                        string DralStr = DralDate.Year.ToString();
                        if (DralDate.Month.ToString().Length == 1)
                            DralStr += "0" + DralDate.Month;
                        else
                            DralStr += DralDate.Month.ToString();
                        if (DralDate.Day.ToString().Length == 1)
                            DralStr += "0" + DralDate.Day;
                        else
                            DralStr += DralDate.Day.ToString();
                        string imaUrlL = HttpContext.Current.Server.MapPath("PaperImages") + @"\";
                        //-----wf--------------
                        //ajaxpro  用到ajax后路径改变  
                        imaUrlL = imaUrlL.Replace(@"\ajaxpro\", @"\");
                        //imaUrlL = @"\\192.168.66.202\image\";
                        imaUrlL = @"\\192.168.66.202\image\";                    //--------------------                    if (imaDat.Tables[0].Rows.Count == 0)
                            sw.WriteLine("<ImageList/>");
                        else//作者
                        {
                            sw.WriteLine("<ImageList>");
                            foreach (DataRow row in imaDat.Tables[0].Rows)
                            {
                                sw.WriteLine("<Image Author='" + row["sAuher"].ToString() + "' PathName='" + row["sImagePath"].ToString() + "' /><![CDATA[ " + row["sDescription"].ToString() + "]]> ");                            //生成图片
                                string filename = imaUrlL + dat.Tables[0].Rows[0]["sSiteChinaName"] + @"\" + DralStr + @"\" + row["sImagePath"].ToString() + "";                            FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite);                            byte[] mydata = new byte[fs.Length];
                                int Length = Convert.ToInt32(fs.Length);
                                fs.Read(mydata, 0, Length);
                                Bitmap image = new Bitmap(fs);
                                //image.Save(Server.MapPath(@"D:\xml\" + row["sImagePath"].ToString() + ""));
                                string ImageSavePath1 = str + @"TempXml\" + row["sImagePath"].ToString();
                                strImagesPath.Add(ImageSavePath1);
                                image.Save(ImageSavePath1);
                                fs.Close();
                                //结束生成图片
                            }
                            sw.WriteLine("</ImageList>");
                        }
                        sw.WriteLine("<PointList>");
                        string zuobiao = dat.Tables[0].Rows[0]["sPointList"].ToString();
                        string zuobiao1 = zuobiao.Substring(zuobiao.IndexOf(",") + 1, (zuobiao.Length - 1) - (zuobiao.IndexOf(",")));
                        string zuobiao2 = zuobiao1.Substring(zuobiao1.IndexOf(",") + 1, (zuobiao1.Length - 1) - (zuobiao1.IndexOf(",")));
                        string zuobiao3 = zuobiao2.Substring(zuobiao2.IndexOf(",") + 1, (zuobiao2.Length - 1) - (zuobiao2.IndexOf(",")));
                        string zuobiao4 = zuobiao3.Substring(zuobiao3.IndexOf(",") + 1, (zuobiao3.Length - 1) - (zuobiao3.IndexOf(",")));
                        string zuobiao5 = zuobiao4.Substring(zuobiao4.IndexOf(",") + 1, (zuobiao4.Length - 1) - (zuobiao4.IndexOf(",")));
                        string zuobiao6 = zuobiao5.Substring(zuobiao5.IndexOf(",") + 1, (zuobiao5.Length - 1) - (zuobiao5.IndexOf(",")));
                        string zuobiao7 = zuobiao6.Substring(zuobiao6.IndexOf(",") + 1, (zuobiao6.Length - 1) - (zuobiao6.IndexOf(",")));
                        string zuobiao8 = zuobiao7.Substring(zuobiao7.IndexOf(",") + 1, (zuobiao7.Length - 1) - (zuobiao7.IndexOf(",")));
                        string zuobiao9 = zuobiao8.Substring(zuobiao8.IndexOf(",") + 1, (zuobiao8.Length - 1) - (zuobiao8.IndexOf(",")));                    sw.WriteLine("<Point X='" + zuobiao.Substring(0, zuobiao.IndexOf(",")) + "' Y='" + zuobiao1.Substring(0, zuobiao1.IndexOf(",")) + "'/>");
                        sw.WriteLine("<Point X='" + zuobiao2.Substring(0, zuobiao2.IndexOf(",")) + "' Y='" + zuobiao3.Substring(0, zuobiao3.IndexOf(",")) + "'/>");
                        sw.WriteLine("<Point X='" + zuobiao4.Substring(0, zuobiao4.IndexOf(",")) + "' Y='" + zuobiao5.Substring(0, zuobiao5.IndexOf(",")) + "'/>");
                        sw.WriteLine("<Point X='" + zuobiao6.Substring(0, zuobiao6.IndexOf(",")) + "' Y='" + zuobiao7.Substring(0, zuobiao7.IndexOf(",")) + "'/>");
                        sw.WriteLine("<Point X='" + zuobiao8.Substring(0, zuobiao8.IndexOf(",")) + "' Y='" + zuobiao9.Substring(0, zuobiao9.IndexOf(",")) + "'/>");
                        sw.WriteLine("</PointList>");
                        sw.WriteLine("</Article>");
                        sw.WriteLine("</ArticleList>");
                        sw.WriteLine("</PageInfoFile>");
                        sw.Flush();
                        sw.Close();
      

  5.   

    我看你的XML文件结构跟  原数据表中的name字段有很大的联系,自己分析处理吧!
      

  6.   


    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;namespace QA
    {
        class Program
        {
            static void Main(string[] args)
            {
                SqlConnection conn;
                string strConn = @"server=WANGQINGKUN\SQLEXPRESS;database=wxd;uid=sa;pwd=password";//连接字符串
                string sql = "select * from _tb where pid='null'";//_tb表名
                SqlDataAdapter da;
                try
                {
                    using (conn = new SqlConnection(strConn))
                    {
                        da = new SqlDataAdapter(sql, conn);
                        DataSet ds = new DataSet();
                        da.Fill(ds);
                        Console.WriteLine(ds.Tables[0].Rows.Count.ToString());
                        using (StreamWriter sw = new StreamWriter(@"F:\tree.xml", false))
                        {
                            sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                sw.WriteLine("<item id='" + ds.Tables[0].Rows[i][0].ToString() + "' text='" + ds.Tables[0].Rows[i][2].ToString() + "'>");
                                DataSet dsSub = new DataSet();
                                sql = "select * from _tb where pid='" + ds.Tables[0].Rows[i][0].ToString() + "'";
                                da = new SqlDataAdapter(sql, conn);
                                da.Fill(dsSub);
                                for (int j = 0; j < dsSub.Tables[0].Rows.Count; j++)
                                {
                                    sw.WriteLine("      <item id='" + dsSub.Tables[0].Rows[j][0].ToString() + "' text='" + dsSub.Tables[0].Rows[j][2].ToString() + "'>");
                                    DataSet dsS = new DataSet();
                                    sql = "select * from _tb where pid='" + dsSub.Tables[0].Rows[j][0].ToString() + "'";
                                    da = new SqlDataAdapter(sql, conn);
                                    da.Fill(dsS);
                                    for (int k = 0; k < dsS.Tables[0].Rows.Count; k++)
                                    {
                                        sw.WriteLine("          <item id='" + dsS.Tables[0].Rows[k][0].ToString() + "' text='" + dsS.Tables[0].Rows[k][2].ToString() + "'>");
                                        sw.WriteLine("          </item>");
                                    }
                                    sw.WriteLine("      </item>");
                                }
                                sw.WriteLine("</item>");
                            }
                            sw.Flush();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.ReadLine();
            }
        }
    }
      

  7.   

    实际中记录是没有顺序的,
    以下是SQL语句深度搜索出来的数据DT,
    level可以代表层次关系,
    name是随便取的,没有任何关系
    id   pid   name  level
    1    null  a     1
    2    1     a1    2
    3    null  b     1
    4    3     b1    2
    5    4     b11   3
    6    3     b2    2
    ....想拼凑成以下XML字符串
    <item id='1' text='a'>
       <item id='2' text='a1'></item>
    </item>
    <item id='3' text='b'>
       <item id='4' text='b1'>
            <item id='5' text='b11'></item>
       </item>
       <item id='6' text='b2'></item>
    </item>
    ....
    盼大虾能够帮忙解决,深表感谢,只能追加到100分了。
      

  8.   

    谢谢lovelj2012,看来只能这样了
        /// <summary>
        /// 获取需要的XML字符串
        /// </summary>
        /// <returns></returns>
        protected string GetTreeXML()
        {
            string xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?><tree id='0'>";
            DataTable dt = dal.GetRootDepartment();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    xmlStr += "<item id='" + dr["DepartmentID"].ToString() + "' text='" + dr["DepartmentName"].ToString() + "'>";                //判断是否为叶子节点
                    if (!dal.IsLeafNode(dr["DepartmentID"].ToString()))
                    {
                        GetTreeChildNodeXML(dr["DepartmentID"].ToString(), ref xmlStr);  
                    }                xmlStr += "</item>";
                }
            }
            return xmlStr + "</tree>"; ;
        }    /// <summary>
        /// 递归搜索
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="xmlStr"></param>
        protected void GetTreeChildNodeXML(string id,ref string xmlStr)
        {
            DataTable dt = dal.GetDepartmentByPID(id);
            {
                if(dt.Rows.Count>0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        xmlStr += "<item id='" + dr["DepartmentID"].ToString() + "' text='" + dr["DepartmentName"].ToString() + "'>";
                        
                        //判断是否为叶子节点
                        if (!dal.IsLeafNode(dr["DepartmentID"].ToString()))
                        {
                            GetTreeChildNodeXML(dr["DepartmentID"].ToString(), ref xmlStr);
                        }                    xmlStr += "</item>";
                    }
                }
            }
        }