首先建立个共同类代码如下:
view plaincopy to clipboardpr?
using ;
using .Collections.Generic;
using .Linq;
using .Text;
using .Xml;
using .IO;
XmlRead
{
public Common
{
public bool GetMessageByKey( xmlPath, AppKey, out AppValue)
{
bool isSuccess = true;
AppValue = "";
(!IsXmlFlieExist(xmlPath))
{
false;
}
try
{
XmlDocument xDoc = XmlDocument;
xDoc.Load(xmlPath);
XmlNode xNode;
XmlElement xElem1;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
(xElem1 != null)
{
AppValue = xElem1.GetAttribute("value");
}
{
}
}
catch (Exception ex)
{
ex.;
isSuccess = false;
}
isSuccess;
}
public bool IsXmlFlieExist( xmlPath)
{
try
{
(File.Exists(xmlPath))
{
true;
}
{
false;
}
}
catch
{
false;
}
}
}
}
using ;
using .Collections.Generic;
using .Linq;
using .Text;
using .Xml;
using .IO;
XmlRead
{
public Common
{
public bool GetMessageByKey( xmlPath, AppKey, out AppValue)
{
bool isSuccess = true;
AppValue = "";
(!IsXmlFlieExist(xmlPath))
{
false;
}
try
{
XmlDocument xDoc = XmlDocument;
xDoc.Load(xmlPath);
XmlNode xNode;
XmlElement xElem1;
xNode = xDoc.SelectSingleNode("//appSettings");
xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
(xElem1 != null)
{
AppValue = xElem1.GetAttribute("value");
}
{
}
}
catch (Exception ex)
{
ex.;
isSuccess = false;
}
isSuccess;
}
public bool IsXmlFlieExist( xmlPath)
{
try
{
(File.Exists(xmlPath))
{
true;
}
{
false;
}
}
catch
{
false;
}
}
}
}
主是下面这样比较简单:
view plaincopy to clipboardpr?
using ;
using .Collections.Generic;
using .Linq;
using .Text;
using .Xml;
XmlRead
{
Program
{
void Main( args)
{
msg;
const xmlPath = "D:\\VS-workspace\\XmlRead\\XmlRead\\MyConfig.xml";
Common .GetMessageByKey(xmlPath, "Errer001", out msg);
Console.WriteLine(msg);
Console.ReadKey;
}
}
}
using ;
using .Collections.Generic;
using .Linq;
using .Text;
using .Xml;
XmlRead
{
Program
{
void Main( args)
{
msg;
const xmlPath = "D:\\VS-workspace\\XmlRead\\XmlRead\\MyConfig.xml";
Common .GetMessageByKey(xmlPath, "Errer001", out msg);
Console.WriteLine(msg);
Console.ReadKey;
}
}
}
参考xml文件如下:
view plaincopy to clipboardpr?
<?xml version="1.0" encoding="utf-8"?>
<.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>
</.Config>
<?xml version="1.0" encoding="utf-8"?>
<.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>
</.Config>
执行结果:
最新评论