xml基本操作和儲存設定檔應用執行個體

來源:互聯網
上載者:User

標籤:

引言:在實際項目中遇到一些關於xml操作的問題,被逼到無路可退的時候終於決定好好研究xml一番。本文首先介紹了xml的基本操作,後面寫了一個經常用到的xml儲存設定檔的執行個體。 

xml常用方法:

定義xml文檔:XmlDocument xmlDoc = new XmlDocument();

初始化xml文檔:xmlDoc.Load("D:\\book.xml");//找到xml檔案

建立根項目:XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", "");

建立節點:XmlElement xeSub1 = xmlDoc.CreateElement("title");

 尋找Employees節點:XmlNode root = xmlDoc.SelectSingleNode("Employees");

添加節點:xe1.AppendChild(xeSub1);

更改節點的屬性:xe.SetAttribute("Name", "李明明");

移除xe的ID屬性:xe.RemoveAttribute("ID");

刪除節點title:xe.RemoveChild(xe2);

 

1 建立xml文檔

因為比較簡單,直接寫方法及結果。

 public void CreateXMLDocument()
        {
            XmlDocument xmlDoc = new XmlDocument();           

//加入XML的聲明段落,<?xml version="1.0" encoding="gb2312"?>
            XmlDeclaration xmlDeclar;
            xmlDeclar = xmlDoc.CreateXmlDeclaration("1.0", "gb2312", null);
            xmlDoc.AppendChild(xmlDeclar);           

//加入Employees根項目
            XmlElement xmlElement = xmlDoc.CreateElement("", "Employees", "");
            xmlDoc.AppendChild(xmlElement);         

//添加節點
            XmlNode root = xmlDoc.SelectSingleNode("Employees");
            XmlElement xe1 = xmlDoc.CreateElement("Node");
            xe1.SetAttribute("Name", "李明");
            xe1.SetAttribute("ISB", "2-3631-4");         

//添加子節點
            XmlElement xeSub1 = xmlDoc.CreateElement("title");
            xeSub1.InnerText = "學習VS";
            xe1.AppendChild(xeSub1);


            XmlElement xeSub2 = xmlDoc.CreateElement("price");
            xe1.AppendChild(xeSub2);
            XmlElement xeSub3 = xmlDoc.CreateElement("weight");
            xeSub3.InnerText = "20";
            xeSub2.AppendChild(xeSub3);


            root.AppendChild(xe1);
            xmlDoc.Save("D:\\book.xml");//儲存的路徑
        }

結果:

<?xml version="1.0" encoding="GB2312"?>
-<Employees>-

  <Node ISB="2-3631-4" Name="李明">

    <title>學習VS</title>-

    <price>

      <weight>20</weight>

    </price>

  </Node>

</Employees>

2 增加節點

XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("D:\\book.xml");//找到xml檔案
            XmlNode root = xmlDoc.SelectSingleNode("Employees");//尋找Employees節點
            XmlElement xe1 = xmlDoc.CreateElement("Node2");//添加Node2節點
            xe1.SetAttribute("Name", "張三");
            XmlElement xeSub1 = xmlDoc.CreateElement("title");//定義子節點
            xeSub1.InnerText = "心情好";
            xe1.AppendChild(xeSub1);//添加節點到Node2
            root.AppendChild(xe1);//添加節點到Employees
            xmlDoc.Save("D:\\book.xml");

結果:

<?xml version="1.0" encoding="GB2312"?>
  -<Employees>

    -<Node ISB="2-3631-4" Name="李明">

      <title>學習VS</title>-

      <price>

        <weight>20</weight>

      </price>

    </Node>-

    <Node2 Name="張三">

      <title>心情好</title>

    </Node2>-

    <Node2 Name="張三">

      <title>心情好</title>

    </Node2>

</Employees>

3 修改節點:

public void ModifyNode()
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("D:\\book.xml");

XmlNodeList nodeList = xmlDocument.SelectSingleNode("Employees").ChildNodes;//擷取Employees節點的所有子節點

foreach (XmlNode xn in nodeList)//遍曆
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("Name") == "李明")
{
xe.SetAttribute("Name", "李明明");//更改節點的屬性

XmlNodeList xnl = xe.ChildNodes;//擷取xe的所有子節點
foreach (XmlNode xn1 in xnl)
{
XmlElement xe2 = (XmlElement)xn1;//將節點xn1的屬性轉換為XmlElement
if (xe2.Name == "title")//找到節點名字為title的節點
{
xe2.InnerText = "今天天氣不好";
}

if (xe2.Name == "price")
{
XmlNodeList xnl2 = xe2.ChildNodes;
foreach (XmlNode xn2 in xnl2)
{
if (xn2.Name == "weight")
{
xn2.InnerText = "88";
}
}
}
}
}
}

xmlDocument.Save("D:\\book2.xml");
}

result:

<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="李明明">
<title>今天天氣不好</title>-<price>
<weight>88</weight>
</price>
</Node>
-<Node2 Name="張三">
<title>心情好</title>
</Node2></Employees>

 

4 刪除節點:

public void ModifyNode()
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load("D:\\book.xml");

XmlNodeList nodeList = xmlDocument.SelectSingleNode("Employees").ChildNodes;//擷取Employees節點的所有子節點

foreach (XmlNode xn in nodeList)//遍曆
{
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("Name") == "李明")
{
xe.SetAttribute("Name", "李明明");//更改節點的屬性

XmlNodeList xnl = xe.ChildNodes;//擷取xe的所有子節點
foreach (XmlNode xn1 in xnl)
{
XmlElement xe2 = (XmlElement)xn1;//將節點xn1的屬性轉換為XmlElement
if (xe2.Name == "title")//找到節點名字為title的節點
{
xe2.InnerText = "今天天氣不好";
}

if (xe2.Name == "price")
{
XmlNodeList xnl2 = xe2.ChildNodes;
foreach (XmlNode xn2 in xnl2)
{
if (xn2.Name == "weight")
{
xn2.InnerText = "88";
}
}
}
}
}
}

xmlDocument.Save("D:\\book2.xml");
}

result:

<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="李明明">
<title>今天天氣不好</title>-<price>
<weight>88</weight>
</price>
</Node>
-<Node2 Name="張三">
<title>心情好</title>
</Node2></Employees>

 


前面介紹了xml的建立、節點的添加、節點的修改和刪除,下面以寫的一個儲存項目設定檔的小例子。

 

舉例說明:

首先在專案檔中建立一個xml文檔:

<?xml version="1.0" encoding="utf-8" ?>
<configurationN>
    <ServerAddress>1143</ServerAddress>
    <ID>192.168</ID>
  </configurationN>

在儲存設定檔時,最主要使用了兩個方法:Load和Save。

Load:初始化xml文檔,以便專案檔擷取具體的xml節點的值。

public void Load(string path)        {            try            {                XmlDocument xmlDocument = new XmlDocument();                xmlDocument.Load(path);                XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn.Name == configuration_ServerAddress)                    {                        ServerAddress = xn.InnerText;                    }                }            }            catch(Exception ex)            { }        }

 

Save:在項目系統中進行修改設定檔值後,需要對xml進行重新儲存

public void Save(string path)        {            try            {                XmlDocument xmlDocument = new XmlDocument();                xmlDocument.Load(path);                XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn.Name == configuration_ServerAddress)                    {                        xn.InnerText = ServerAddress;                    }                }                xmlDocument.Save(path);            }            catch (Exception ex)            { }        }

 


此處將所有代碼都貼出來,方便下次實現。因為項目是WPF檔案,而且都是簡單控制項,所以只貼出後台代碼。

class ConfigurationManager:INotifyPropertyChanged     {        public const string managerNode = "configurationN";//根節點        public const string configuration_ServerAddress = "ServerAddress";//子節點        private string _ServerAddress;        public string ServerAddress        {            get { return _ServerAddress; }            set            {                _ServerAddress = value;                NotifyPropertyChanged("ServerAddress");            }        }        public void Load(string path)        {            try            {                XmlDocument xmlDocument = new XmlDocument();                xmlDocument.Load(path);                XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn.Name == configuration_ServerAddress)                    {                        ServerAddress = xn.InnerText;                    }                }            }            catch(Exception ex)            { }        }        public void Save(string path)        {            try            {                XmlDocument xmlDocument = new XmlDocument();                xmlDocument.Load(path);                XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn.Name == configuration_ServerAddress)                    {                        xn.InnerText = ServerAddress;                    }                }                xmlDocument.Save(path);            }            catch (Exception ex)            { }        }        public event PropertyChangedEventHandler PropertyChanged;        private void NotifyPropertyChanged(string propertyName)        {            if (PropertyChanged != null)            {                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));            }        }        public static ConfigurationManager Instance = new ConfigurationManager();    }public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            Start();            this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString();        }        private string path = "CONFIG\\System.xml";        private void button1_Click(object sender, RoutedEventArgs e)        {            ConfigurationManager.Instance.ServerAddress = this.tb1.Text;            ConfigurationManager.Instance.Save(path);        }        private void button2_Click(object sender, RoutedEventArgs e)        {            Application.Current.Shutdown();        }        private void Start()        {            ConfigurationManager.Instance.Load(path);        }    }
class ConfigurationManager:INotifyPropertyChanged     {        public const string managerNode = "configurationN";//根節點        public const string configuration_ServerAddress = "ServerAddress";//子節點        private string _ServerAddress;        public string ServerAddress        {            get { return _ServerAddress; }            set            {                _ServerAddress = value;                NotifyPropertyChanged("ServerAddress");            }        }        public void Load(string path)        {            try            {                XmlDocument xmlDocument = new XmlDocument();                xmlDocument.Load(path);                XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn.Name == configuration_ServerAddress)                    {                        ServerAddress = xn.InnerText;                    }                }            }            catch(Exception ex)            { }        }        public void Save(string path)        {            try            {                XmlDocument xmlDocument = new XmlDocument();                xmlDocument.Load(path);                XmlNodeList xnl = xmlDocument.SelectSingleNode(managerNode).ChildNodes;                foreach (XmlNode xn in xnl)                {                    if (xn.Name == configuration_ServerAddress)                    {                        xn.InnerText = ServerAddress;                    }                }                xmlDocument.Save(path);            }            catch (Exception ex)            { }        }        public event PropertyChangedEventHandler PropertyChanged;        private void NotifyPropertyChanged(string propertyName)        {            if (PropertyChanged != null)            {                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));            }        }        public static ConfigurationManager Instance = new ConfigurationManager();    }public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            Start();            this.tb1.Text = ConfigurationManager.Instance.ServerAddress.ToString();        }        private string path = "CONFIG\\System.xml";        private void button1_Click(object sender, RoutedEventArgs e)        {            ConfigurationManager.Instance.ServerAddress = this.tb1.Text;            ConfigurationManager.Instance.Save(path);        }        private void button2_Click(object sender, RoutedEventArgs e)        {            Application.Current.Shutdown();        }        private void Start()        {            ConfigurationManager.Instance.Load(path);        }    }

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.