(23)C#XML操作

APP.config是一个典型的XML文件

打开vs2008在项目上右键-添加-新建项

选择应用程序配置文件,默认名称为APP.config,新建打开后默认代码如下

<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>

所有的代码都要写在<configuration>     </configuration>之间

 

 

 C#空间要引入using System.Configuration;

1、appSettings配置节

 <appSettings>
  <add key="key1" value="value1" />
  <add key="key2" value="value2" />
 </appSettings>

 

C#读取appSettings配置节

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace xml
{
    class Program
    {
        static void Main(string[] args)
        {
              string str = ConfigurationSettings.AppSettings["key1"];//过时
        string str= ConfigurationManager.AppSettings["key1"];
            Console.WriteLine(str);
              Console.ReadLine();
        }
    }
}

 

 

 

 运行结果

作用:可以在程序安装好后通过修改appConfig改变字符串的值,达到某些目的

2、applicationSettings配置节

 <applicationSettings>

    <WinService>

        <setting name="WinService_Login" serializeAs="String">

            <value>http://192.168.208.65:6888/abc/mm</value>

        </setting>

    </WinService>

</applicationSettings>      

C#读取applicationSettings配置节

 string sUrl =  MyProject .Properties.Settings.Default. WebSrv ; 

 

applicationSettings配置节和appSettings配置节同一个效果都是读取值

用appSettings读取方式,需要手动添加app.config内容(appSettings字段),
而且使用ConfigurationManager时要加上 using System.Configuration; 同时添加System.Configuration.dll引用
还有一点就是应用程序目录必须存在MyProject.exe.config文件,否则exe会打不开!
 
使用applicationSettings的优点是直接可以在Settings界面中编辑内容,还可以构建和测试connectionString字段, 参数配置更直观.
应用程序目录不必一定要有MyProject.exe.config文件,如果没有该文件,读出的值是编译时设置的值,否则读取该文件中的值.

3、connectionStrings配置节

 

如果无法读取文件需要再VS中添加引用 System.configuration.dll,否则不能使用ConfigurationManager这个类.

 

  <connectionStrings>
    <!-- Oracle 连接-->
    <add name="connectionName" connectionString="data source=orcl;persist security info=True;user id=用户名;password=密码;"></add>
  </connectionStrings>

 

 

 

 

读取connectionStrings

string connectionString = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString(); 

 

DataTable与XML转换

#region 将datatable解析成xml的方法

        public static string DataTable2XML(DataTable table)
        {
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 4;

            writer.WriteStartDocument();

            writer.WriteStartElement("table");

            writer.WriteStartElement("rowCount");
            writer.WriteString(table.Rows.Count.ToString());
            writer.WriteEndElement();//endrowcount

            writer.WriteStartElement("headCount");
            writer.WriteString(table.Columns.Count.ToString());
            writer.WriteEndElement();//endheadcount

            writer.WriteStartElement("head");
            int hn = 1;
            foreach (DataColumn col in table.Columns)
            {
                writer.WriteStartElement("h" + hn.ToString());
                writer.WriteString(col.ColumnName.ToString());
                writer.WriteEndElement();//endhn
                hn++;
            }
            writer.WriteEndElement();//endhead

            writer.WriteStartElement("body");
            int rn = 1;
            foreach (DataRow row in table.Rows)
            {
                writer.WriteStartElement("r" + rn.ToString());
                for (int cn = 1; cn < table.Columns.Count + 1; cn++)
                {
                    writer.WriteStartElement("r" + rn.ToString() + "c" + cn.ToString());
                    writer.WriteString(row[cn - 1].ToString());
                    writer.WriteEndElement();//endrncn
                }
                writer.WriteEndElement();//endrn
                rn++;
            }

            writer.WriteEndElement();//endbody
            writer.WriteEndElement();//endtable

            writer.Flush();

            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);
            string ret = reader.ReadToEnd();
            //SaveXMLFile(ret);
            writer.Close();
            return ret;
        }

#endregion

 

  #region 解析xml文件到内存datatable
        private DataTable XML2DataTable(string xml)
        {
            int rowCount, headCount;
            DataTable table = new DataTable();

            //XmlDocument doc = new XmlDocument();
            //string xmlContent = File.ReadAllText(@"c:\物料(1).txt", Encoding.Default);
            //doc.LoadXml(xmlContent);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            SaveXMLFile(doc);
            foreach (XmlNode nodeDoc in doc.ChildNodes)
            {
                if (nodeDoc.Name.Equals("table"))
                {
                    foreach (XmlNode nodeTableChild in nodeDoc.ChildNodes)
                    {
                        if (nodeTableChild.Name.Equals("rowCount"))
                        {
                            Console.WriteLine(nodeTableChild.InnerText);
                            rowCount = Convert.ToInt32(nodeTableChild.InnerText);
                        }
                        if (nodeTableChild.Name.Equals("headCount"))
                        {
                            Console.WriteLine(nodeTableChild.InnerText);
                            headCount = Convert.ToInt32(nodeTableChild.InnerText);
                        }
                        if (nodeTableChild.Name.Equals("head"))
                        {
                            foreach (XmlNode nodeHeadChild in nodeTableChild.ChildNodes)
                            {
                                Console.WriteLine(nodeHeadChild.InnerText);
                                table.Columns.Add(nodeHeadChild.InnerText);
                            }
                        }
                        if (nodeTableChild.Name.Equals("body"))
                        {
                            foreach (XmlNode nodeBodyChild in nodeTableChild.ChildNodes)
                            {
                                if (!nodeBodyChild.Name.Contains("c"))
                                {
                                    Console.WriteLine(nodeBodyChild.Name);
                                    DataRow row = table.NewRow();
                                    for (int i = 0; i < table.Columns.Count; i++)
                                    {
                                        Console.WriteLine(nodeBodyChild.ChildNodes[i].InnerText);
                                        row[i] = nodeBodyChild.ChildNodes[i].InnerText;
                                    }
                                    table.Rows.Add(row);
                                }
                            }
                        }
                    }
                }
            }
            if (table.Rows.Count == 0)
            {
                throw new Exception("xml中没有包含任何数据!");
            }
            return table;
        }

        private void SaveXMLFile(XmlDocument doc)
        {
            string path = Server.MapPath("") + "\\XML";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = path + "\\E2M_" + Guid.NewGuid().ToString() + ".xml";
            fileName = fileName.Replace('-', '_');
            doc.Save(fileName);
        }
        #endregion

 

posted @ 2016-11-19 15:28  富坚老贼  阅读(224)  评论(0编辑  收藏  举报