您的位置:首页 > 其它

xml文件的读取---根据XMl文件的ID读取对应的内容

2009-07-22 18:01 162 查看
项目中经常遇到一些读取xml文件的方法,特别是在进行错误处理的情况下,要根据ErrId来获取Error内容,网上这一方面的东西比较零散,今天花了点时间整理了一下,写了一个小例子,拿来和大家分享一下。

首先建立一个共同的类,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace XmlRead
{
public class Common
{
public static bool GetMessageByKey(string xmlPath, string AppKey, out string AppValue)
{
bool isSuccess = true;
AppValue = "";
if (!IsXmlFlieExist(xmlPath))
{
return false;
}
try
{
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlPath);
XmlNode xNode;
XmlElement xElem1;

xNode = xDoc.SelectSingleNode("//appSettings");

xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
if (xElem1 != null)
{
AppValue = xElem1.GetAttribute("value");
}
else
{
}
}
catch (Exception ex)
{
ex.ToString();
isSuccess = false;
}
return isSuccess;
}

public static bool IsXmlFlieExist(string xmlPath)
{
try
{
if (File.Exists(xmlPath))
{
return true;
}
else
{
return false;
}

}
catch
{
return false;
}
}

}
}


主程序是下面这样的,比较简单:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XmlRead
{
class Program
{
static void Main(string[] args)
{
string msg;
const string xmlPath = "D://VS-workspace//XmlRead//XmlRead//MyConfig.xml";
Common .GetMessageByKey(xmlPath, "Errer001", out msg);
Console.WriteLine(msg);
Console.ReadKey();
}
}
}


参考的xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<System.Config>
<appSettings>
<add key="ConnectString" value="D085D536F765EEB74123E527CEC0F564" />
<add key="Message2" value="D085D536F765EEB74123E527CEC0F564" />
<add key="Message3" value="D085D536F765EEB74123E527CEC0F564" />

<add key="Errer001" value="Host is already using!" />
<add key="Errer002" value="Please input halfsize number!" />
</appSettings>
</System.Config>

执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: