如何讀取XML文檔 c#

來源:互聯網
上載者:User

第一步 先建立一個xml文檔 看文檔如下 也可以用代碼來寫入xml

<?xml version="1.0" encoding="gb2312"?><paramentList>      <paramentEntity id="niname">             <id>{$Niname$}</id>            <value>稱呼</value>        </paramentEntity>    <paramentEntity id="sign">            <id>{$Sign$}</id>            <value>簽名</value>        </paramentEntity></paramentList>

第二步 寫一個對於的實體類

using System;using System.Collections.Generic;using System.Text;namespace APlusEmail.Model{    public class ParamentEntity    {        private string id;        public string Id        {            get { return id; }            set { id = value; }        }        private string value;        public string Value        {            get { return this.value; }            set { this.value = value; }        }    }}

第三步 寫一個工具類 來操作

using System;using System.Collections.Generic;using System.Text;using APlusEmail.Model;using System.Xml;namespace APlusEmail.Common{    public static class XMLHelper    {        public static List<ParamentEntity> GetAllParament(string xmlPath)        {            List<ParamentEntity> paramentList = new List<ParamentEntity>();            //建立xmldoc對象            XmlDocument xmlDoc = new XmlDocument();            //裝載xml            xmlDoc.Load(xmlPath);            //擷取xml的節點            XmlNode xn = xmlDoc.SelectSingleNode("paramentList");            //擷取該節點的所有子節點            XmlNodeList xnl=xn.ChildNodes;            //遍曆            foreach(XmlNode xnf in xnl)            {                    XmlElement xe=(XmlElement)xnf;                 //擷取屬性                //Console.WriteLine(xe.GetAttribute("genre"));                //顯示內容值                    //Console.WriteLine(xe.GetAttribute("ISBN"));                 //遍曆裡面的某一個節點                XmlNodeList xnf1=xe.ChildNodes;                ParamentEntity parementEntity = new ParamentEntity();                parementEntity.Id = xnf1[0].InnerText;                parementEntity.Value = xnf1[1].InnerText;                // Console.WriteLine(xn2.InnerText);//顯示子節點點文本                paramentList.Add(parementEntity);            }            return paramentList;        }    }}

這樣就返回一個對應的實體列表了 就可以供使用了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.