XML(eXtensible Markup Language,可扩展标记语言)是一种通用的标记语言,主要用于存储和传输结构化数据。它的设计目标是兼具可读性和机器可处理性,广泛应用于如下场景:
- 数据存储与交换:不同应用程序之间数据交换。
- Web服务与API通信:Web服务的标准数据格式,用于网络传输结构化信息。
- 系统配置参数文件:使用XML定义配置参数,因其层次结构清晰且易于解析。
- 文档标记:XML可用于标记文档内容,支持自定义标签描述语义。
- 数据库与数据序列化:XML可作为数据库导出格式或对象序列化格式。
- 跨平台兼容性:XML与编程语言无关,几乎所有语言(Java、Python、C#等)都提供XML解析库(如DOM、SAX)。
1、创建XML格式文件
(1)准备一个数据表:
string XMLFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XMLTest.xml");
DataTable dt = new DataTable();dt.Columns.Add("Id");dt.Columns.Add("Name");dt.Columns.Add("Code");dt.Columns.Add("YuWen");dt.Columns.Add("ShuXue");dt.Columns.Add("YingYu");dt.Columns.Add("TiYu");
for (int i = 0; i < 10; i++){    DataRow dr = dt.NewRow();    dr["Id"] = i;    dr["Name"] = "Name" + i.ToString();    dr["Code"] = "Code" + i.ToString();    dr["YuWen"] = 100 + i;    dr["ShuXue"] = 200 + i;    dr["YingYu"] = 300 + i;    dr["TiYu"] = 400 + i;    dt.Rows.Add(dr);}
(2)将数据表转换为A格式:
bool RetState = XmlFileHelper.Handle.DataTableToXMLA(dt, XMLFilePath);
(3)将数据表转换为B格式:
RetState = XmlFileHelper.Handle.DataTableToXMLB(dt, XMLFilePath);
(4)XML格式转换帮助类:
public class XmlFileHelper{    private static XmlFileHelper handle = null;    public static XmlFileHelper Handle    {        get        {            if (handle == null)            {                handle = new XmlFileHelper();            }            return handle;        }    }
    #region 内置函数,通用DataTable与XML文件相互转换       
    #region DataTable转换为XML文件 格式A                            public bool DataTableToXMLA(DataTable data, string SaveXMLFilePath)    {        bool RetState = false;        DataSet ds = new DataSet();        ds.Tables.Add(data.Copy());
        try        {            using (MemoryStream stream = new MemoryStream())            {                using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))                {                    ds.WriteXml(writer, XmlWriteMode.WriteSchema);                    int nCount = (int)stream.Length;                    byte[] arr = new byte[nCount];                    stream.Seek(0, SeekOrigin.Begin);                    stream.Read(arr, 0, nCount);                    UTF8Encoding utf = new UTF8Encoding();                    string strContent = utf.GetString(arr).Trim();                    using (StreamWriter sw = new StreamWriter(SaveXMLFilePath))                    {                        string NewStr = strContent;                        NewStr = NewStr.Replace("><xs", ">\r\n<xs").Replace("></xs", ">\r\n</xs").Replace("schema><Table1", "schema>\r\n<Table1").Replace("Table1><Table1", "Table1>\r\n<Table1").Replace("></NewDataSet", ">\r\n</NewDataSet");                        sw.WriteLine(NewStr);                        sw.Close();                        writer.Close();                    }                }            }            RetState = true;        }        catch (System.Exception ex)        {            RetState = false;            throw new Exception(ex.Message);        }        return RetState;    }    #endregion
    #region DataTable转换为XML文件 格式B                                   public bool DataTableToXMLB(DataTable dt, string xmlFilePath)    {        bool RetState = false;        try        {            XElement xAld = new XElement("DataTable", new XAttribute("Count", dt.Rows.Count));            for (int i = 0; i < dt.Rows.Count; i++)            {                XElement xProduct = new XElement("Row", new XAttribute("Index", (i + 1).ToString()));
                for (int j = 0; j < dt.Columns.Count; j++)                {                    xProduct.Add(new XElement(dt.Columns[j].ColumnName, dt.Rows[i][j].ToString()));                }                xAld.Add(xProduct);            }
            xAld.Save(xmlFilePath);        }        catch (Exception)        {            RetState = false;        }        return RetState;    }    #endregion
    #region XML文件转换为DataTable                        public DataTable XMLToDataTable(string XMLFilePath)    {        DataTable ReData = new DataTable();        DataSet ds = new DataSet();        try        {            if (!File.Exists(XMLFilePath)) return new DataTable();
            using (StreamReader sr = new StreamReader(XMLFilePath))            {                string strXmlContent = sr.ReadToEnd();                using (StringReader stream = new StringReader(strXmlContent))                {                    using (XmlTextReader reader = new XmlTextReader(stream))                    {                        ds.ReadXml(reader);                        reader.Close();                        stream.Close();                        sr.Close();                    }                }            }            if (ds.Tables.Count > 1)                ReData = ds.Tables[1];            else                ReData = ds.Tables[0];        }        catch (System.Exception vErr)        {            ReData = new DataTable();            throw new Exception(vErr.Message);        }        return ReData;    }    #endregion
    #endregion  }
新款S119无人机GPS定位返航带屏高级航拍四轴飞行器8k长续航
青少年160Pro-多功能编程无人机C类科教馆竞赛教具用无人机飞行器
BC230竞赛编程无人机青少年教学编程无人机C类科教馆竞赛类教具1
无人机编程入门
(1)自定义格式(主表与子表嵌套格式),内容列属性描述根据需求调整;private static void CreateUserXmlFile(string xmlFilePath){
    XElement xAld = new XElement("大标题", new XAttribute("version", "1.0"));
        XElement xProduct = new XElement("主表标题", new XAttribute("主表标识名称", "主表标识名称值"),                    new XElement("列名1", "值1"),                    new XElement("列名2", "值2"),                    new XElement("子表行数", "10"),                                        new XElement("列名N", "值N")                    );    xAld.Add(xProduct);
        for (int i = 0; i < 10; i++)    {        XElement xVersion = new XElement("子表标题", new XAttribute("Index", (i + 1).ToString()),                     new XElement("列名1", "值1"),                     new XElement("列名2", "值2"),                                          new XElement("列名N", "值N")                    );        xAld.Add(xVersion);    }
        xAld.Save(xmlFilePath);}

XElement xe = XElement.Load(xmlFilePath);var Product = (from ele in xe.Elements("主表标题") select ele).SingleOrDefault();if (xProduct != null){    int Count = int.Parse(xProduct.Element("子表行数").Value);    for (int i = 1; i <= Count; i++)    {        var xVersion = (from ele in xe.Elements("子表标题") where ele.Attribute("Index").Value.Equals(i.ToString()) select ele).SingleOrDefault();        if (xVersion != null)        {            string v1 = xVersion.Element("列名1").Value.Trim().ToUpper();            string v2 = xVersion.Element("列名2").Value.Trim().ToUpper();            string vN = xVersion.Element("列名N").Value.Trim().ToUpper();        }    }}
阅读原文:原文链接
该文章在 2025/7/21 10:30:02 编辑过