C#读XML文件
<?xml version="1.0" encoding="UTF-8"?>
<SynonymRecord>
<SynonymName>Neoplasms</SynonymName>
<SynonymName>Cancers</SynonymName>
</SynonymRecord>
/// <summary>
/// 读XML文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
ReaderXML(@Server.MapPath("XMLFile.xml"));
}
private void ReaderXML(string strPath)
{
string Msg="";
XmlTextReader xtr = new XmlTextReader(strPath);
while(xtr.Read())
{
switch(xtr.NodeType)
{
case XmlNodeType.Element:
{
Response.Write(Msg += string.Format("开始元素{0}\n", xtr.Name) + "<br>");
//是否有属性
if(xtr.HasAttributes)
{
//读属性
for(int i = 0;i < xtr.AttributeCount;i++)
{
xtr.MoveToAttribute(i);
Response.Write(Msg += string.Format("属性{0} = '{1}'\n", xtr.Name, xtr.Value) + "<br>");
}
}
break;
}
case XmlNodeType.Text:
{
Response.Write(Msg += string.Format("内容{0}\n", xtr.Value) + "<br>");
break;
}
case XmlNodeType.EndElement:
{
Response.Write(Msg += string.Format("结束元素{0}\n", xtr.Name) + "<br>");
break;
}
}
}
xtr.Close();
}
}