c# 读取XML文件的简单代码

发布时间:2020-01-31编辑:脚本学堂
c#实现xml文件的读取,主要用到了System.Xml,有需要的朋友,可以参考下。

1、xml文件
 

复制代码 代码示例:
<?xml version="1.0" encoding="UTF-8"?>
 <SynonymRecord>
<SynonymName>Neoplasms</SynonymName>
<SynonymName>Cancers</SynonymName>
</SynonymRecord>

2、读取xml文件的代码
 

复制代码 代码示例:

/// <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();
    }
}