using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace ReadXml
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> DicXmlPairs = new MyXMLReader().DicXmlPairs;
string sql=string.Empty;
if (DicXmlPairs.TryGetValue("id1", out sql))
{
Console.WriteLine(sql);
}
Console.ReadKey();
}
public class MyXMLReader
{
public Dictionary<string, string> DicXmlPairs
{
get
{
return this.GetAllXmlContent();
}
}
private string key = string.Empty;
/// <summary>
/// 获取一个Xml文件的 key value
/// </summary>
/// <param name="xmlFile"></param>
/// <param name="dicXmlContents"></param>
private void AnalyzeXml(FileInfo xmlFile, ref Dictionary<string, string> dicXmlContents)
{
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlFile.FullName);
reader.WhitespaceHandling = WhitespaceHandling.None;
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
if ("sql".Equals(reader.Name) && reader.HasAttributes && 1 == reader.AttributeCount)
{
key = reader.GetAttribute("name");
}
}
break;
case XmlNodeType.CDATA:
{
dicXmlContents.Add(key, reader.ReadContentAsString());
}
break;
default:
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
/// <summary>
/// 获得所有XML文件中的key value
/// </summary>
private Dictionary<string,string> GetAllXmlContent()
{
Dictionary<string, string> dicXmlContents = new Dictionary<string, string>();
string xmlPath = AppDomain.CurrentDomain.BaseDirectory;
List<FileInfo> lstFiles = new List<FileInfo>();
GetXMLFiles(new DirectoryInfo(xmlPath), ref lstFiles);
foreach (FileInfo xmlfile in lstFiles)
{
AnalyzeXml(xmlfile, ref dicXmlContents);
}
return dicXmlContents;
}
//获取全部的Xml文件
private void GetXMLFiles(DirectoryInfo xmlDir, ref List<FileInfo> lstFiles)
{
foreach (FileInfo files in xmlDir.GetFiles())
{
if (files.Extension.ToUpper().EndsWith(".XML"))
{
lstFiles.Add(files);
}
}
foreach (DirectoryInfo subDir in xmlDir.GetDirectories())
{
GetXMLFiles(subDir, ref lstFiles);
}
}
}
}
}
Xml文件 内容:
<?xml version="1.0" encoding="utf-8" ?>
<sql-definations>
<!--lalalaalala-->
<sql name="id1">
<![CDATA[
select xxx from xxx where xxxx=xx
]]>
</sql>
</sql-definations>