1. 程式人生 > >C#讀取xml文件

C#讀取xml文件

contex namespace count mon ren ESS ext class als

~/Config/Config.xml 文件: 

<?xml version="1.0" encoding="utf-8" ?>
<project>
<function name="Account">
  <attribute name="UserID" value="123456"></attribute>
</project>
公用類和方法:
using
System; using System.Xml; namespace Common { /// <summary> /// Summary description for XMLHelper.
/// </summary> public class XMLHelper { public XMLHelper() { // // TODO: Add constructor logic here // } public static string ReadXML(string Function,string Attribute) { string returnValue = string
.Empty; try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(System.Web.HttpContext.Current.Server.MapPath("~/Config/Config.xml")); XmlNode xn=xmlDoc.SelectSingleNode("project"); XmlNodeList xnl=xn.ChildNodes;
foreach(XmlNode xnf in xnl) { if(xnf.Attributes.GetNamedItem("name").Value.Equals(Function)) { XmlNodeList xnl2 = xnf.ChildNodes; foreach(XmlNode xnf2 in xnl2) { XmlElement xe=(XmlElement)xnf2; if(xe.GetAttribute("name").Equals(Attribute)) { returnValue = xe.GetAttribute("value"); break; } } break; } } return returnValue; } catch(Exception ex) { return ex.Message; } } } }
調用:
using Common;
string
userid= XMLHelper.ReadXML("Account", "UserID"); //userid="123456".

C#讀取xml文件