ASP.NET操作XML讀取和儲存

來源:互聯網
上載者:User
XML代碼

<?xml version="1.0" encoding="utf-8"?>
<root>
  <env>
    <param name="rate" value="3" />
    <param name="url" value="3" />
  </env>
  <vr startpano="start" width="10" height="540" x="0" y="0" >
    <pano name="url" url="Car/Model/InteriorPanorama/BJXD_i30/S-max.jpg">
    </pano>
  </vr>
  <background file="control/bg.jpg">
  </background>
</root>後台cs代碼using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 SomePages_OperateXML : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = ReadXML();
        lblReadXML.Text = str;
        SaveXML();
    }
    private string  ReadXML()
    {
        string strReturn = string.Empty;

        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/images/config.xml"));
        XmlElement root = doc.DocumentElement;
       
        //定義要求匹配項 name="url"
        string path = @"//*[@name='url']";
        //在當前節點根據匹配項進行尋找
        foreach (XmlNode node in root.SelectNodes(path))
        {
            strReturn += "匹配項:" + path;
            strReturn += "節點:" + node.Name;
            strReturn += "<br/>";
        }

        //直接尋找指定節點讀取值
        XmlElement x = (XmlElement)root.SelectSingleNode("vr");
        if (x != null)
        {
            strReturn += x.GetAttribute("startpano");
        }
        return strReturn;

    }
    private void SaveXML()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/images/config.xml"));

        XmlElement root = doc.DocumentElement;
        XmlElement x = (XmlElement)root.SelectSingleNode("vr");

        if (x != null)
        {
            //設定節點屬性
            x.SetAttribute("width1", "10");
            //建立節點
            XmlElement x1 = doc.CreateElement("test");
            x1.SetAttribute("width", "100");
            //添加節點
            x.AppendChild(x1);
            //儲存xml
            doc.Save(Server.MapPath("~/images/config.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.