日期:2014-05-17  浏览次数:20825 次

C#中怎么把字段值转成XML中的属性而不是节点?求教!
C# code

    /// <summary>
    /// 将DataTable对象转换成XML字符串
    /// </summary>
    /// <param name="dt">DataTable对象</param>
    /// <returns>XML字符串</returns>
    public static string CDataToXml(DataTable dt)
    {
        if (dt != null)
        {
            MemoryStream ms = null;
            XmlTextWriter XmlWt = null;
            try
            {
                ms = new MemoryStream();
                //根据ms实例化XmlWt
                XmlWt = new XmlTextWriter(ms, Encoding.Unicode);
                //获取ds中的数据
                dt.WriteXml(XmlWt);
                int count = (int)ms.Length;
                byte[] temp = new byte[count];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(temp, 0, count);
                //返回Unicode编码的文本
                UnicodeEncoding ucode = new UnicodeEncoding();
                string returnValue = ucode.GetString(temp).Trim();
                return returnValue;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                //释放资源
                if (XmlWt != null)
                {
                    XmlWt.Close();
                    ms.Close();
                    ms.Dispose();
                }
            }
        }
        else
        {
            return "";
        }
    }

    public string GetXmlString()
    {
        DataTable dt = new DataTable();
        dt.TableName = "filepath";
        dt.Columns.Add("id", typeof(int));
        dt.Columns.Add("name", typeof(string));
        dt.Rows.Add(1, "a");
        dt.Rows.Add(2, "b");
        dt.Rows.Add(3, "c");
        dt.Rows.Add(4, "d");
        dt.Rows.Add(5, "e");
        return CDataToXml(dt);
        /*
         得到的结果是这个样子的:
         <DocumentElement>
             <filepath><id>1</id><name>a</name></filepath>
             <filepath><id>2</id><name>b</name></filepath>
             <filepath><id>3</id><name>c</name></filepath>
             <filepath><id>4</id><name>d</name></filepath>
             <filepath><id>5</id><name>e</name></filepath>
         </DocumentElement>
         */

        /* 我想要的结果是这个样子
        <?xml version="1.0" encoding="utf-8"?>
        <root>
            <filepath id="1" name="a"/>
            <filepath id="2" name="b"/>
            <filepath id="3" name="c"/>
            <filepath id="4" name="d"/>
            <filepath id="5" name="e"/>
        </root>
        */
    }



------解决方案--------------------
xmldocument或linq的xdocument自己去一条条写进去,属性就是赋值Attribute值
http://www.cnblogs.com/yukaizhao/archive/2011/07/19/csharp_xmldocument_access_xml.html
http://www.cnblogs.com/ycdx2001/archive/2009/04/07/1430670.html
------解决方案--------------------
简单的话,你可以自己遍历datatable后拼接。
xml就是一个字符串,大多时候拼接数据也是可以的。(稍微需要注意的是字符的转义,比如对"'<>的处理)
------解决方案--------------------
也可以使用xslt进行转换
------解决方案--------------------
生成xml后,再自己转换一下,把子元素转换为属性。