.Net 讀取xml

來源:互聯網
上載者:User

標籤:節點   檔案路徑   包括   gif   指定   nbsp   value   http   tor   

一、常規方法

1.知識介紹

      //初始化一個xml對象        XmlDocument xml = new XmlDocument();        //載入xml檔案        xml.Load("檔案路徑");        //讀取指定的節點        XmlNode xmlNode = xml.SelectSingleNode("/節點名");        //判斷節點下是否有子節點        xmlNode.HasChildNodes;        //讀取節點下的所有子節點        XmlNodeList xmlNodeList = xmlNode.ChildNodes;        //讀取同名同級多個節點列表        XmlNodeList xmlNodeList = xml.SelectNodes("/root/節點名");        //讀取節點的屬性        string attribute = xmlNode.Attributes["屬性名稱"].Value;        //讀取節點的文本        string value = xmlNode.InnerText;        //建立一個新的節點        XmlNode xmlNode = xml.CreateElement("節點名");        //儲存xml檔案        xml.Save("檔案路徑");

2.執行個體

        //建立並初始化一個xml對象        XmlDocument xml = new XmlDocument();        //載入xml檔案        try        {            xml.Load(HttpContext.Current.Server.MapPath("~/datafunc/allmana.xml"));        }        catch (Exception)        {            throw new ExceptionMsg(4, "載入xml檔案失敗!");         }        //讀取節點        XmlNode snXmlNode = xml.SelectSingleNode("/Config/SystemName");        SystemName = snXmlNode.InnerText;

二、Linq讀取xml檔案

1.知識介紹

a.XDocument,這是Linq to xml常用類之一,提供處理xml文檔的方法,包括聲明、注釋各處理指示。

b.XElement 它表示一個xml元素,可以用此類建立元素,更改元素內容;添加、更改、刪除子項目;向元素中添加屬性;或以文字格式設定序列化元素內容。

c.XAttribute  它用來處理元素的屬性

2.執行個體

建立xml檔案

//建立XDocument對象,並執行個體化對象        XDocument xdoc = new XDocument(            //xml的格化與編碼            new XDeclaration("1.0", "utf-8", "yes"),            //建立元素            new XElement("Config",            //建立元素,並做上一元素的子項目                new XElement("System",                //建立元素的屬性                new XAttribute("Name", "allmana"),                new XElement("StoreName", "省婦幼店")                ),            //建立同級元素            new XElement("System",                new XAttribute("Name", "allmana1"),                new XElement("StoreName", "市婦幼店")                )                )                );        //儲存xml檔案        xdoc.Save(HttpContext.Current.Server.MapPath("~/DataConfig/Config.xml"));

.Net 讀取xml

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.