首頁 > 軟體

C#讀寫xml檔案方法總結(超詳細!)

2023-02-24 06:02:43

C#寫入xml檔案

1、XmlDocument

1。我認為是最原始,最基本的一種:利用XmlDocument向一個XML檔案裡寫節點,然後再利用XmlDocument儲存檔案。
首先載入要寫入的XML檔案,但是如果沒有的,就要新建,在新建的過程中,要有寫入的程式碼;

XmlDocument doc = new XmlDocument();
            try
            {
                doc.Load("new.xml");
            }
            catch
            {
                XmlTextWriter xtw = new XmlTextWriter("new.xml", Encoding.UTF8);
                //新建XML檔案        
                xtw.WriteStartDocument();
                xtw.WriteStartElement("gnode");
                // gnode根節點                 
                xtw.WriteStartElement("myxm1");
                // gnode根節點下的元素myxmls             
                xtw.WriteEndElement();
                xtw.WriteEndElement();
                xtw.WriteEndDocument();
                xtw.Close();
                doc.Load("new.xml");
            }
            XmlNode xn = doc.DocumentElement;
            //找到根節點     
            XmlElement xe = doc.CreateElement("myxml2");
            //在根節點下建立元素,如果是屬性,則用XmlAttribute; 
            xe.InnerText = "薪薪程式碼hahaha";
            //給子節點寫入文位元組點(值)     
            xn.AppendChild(xe);
            //根節點將其納入         
            doc.Save("new2.xml");
            //利用XmlDocument儲存檔案
        }

注意點:在新建根節點的時候,WriteStartElement,只能巢狀,也就是隻能有一個根節點。

2、DataSet物件裡的值來生成XML檔案

應用到資料庫,將資料庫的DataSet物件裡的值來生成XML檔案的元素;

using (SqlConnection con = new SqlConnection("Server=.;DataBase=HGSTUDY;uid=sa;pwd=yao"))
            {
                con.Open();
                SqlCommand command = new SqlCommand("select * from GL_STUDY", con);
                command.CommandType = CommandType.Text;
                DataSet ds = new DataSet("DATASET");
                //DATASET將成為XML檔案中的根節點名稱,否則系統將其命名為NewDataSet      
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = command;
                sda.Fill(ds, "DATATABLE");
                //DATATABLE為所生成XML檔案中的子節點名稱,否則系統將其命名為Table。   
                ds.WriteXml("dbxml.xml");
                // DataSet的方法WriteXml將資料寫入到XML檔案,就是這麼一句話。如果不儲存到檔案,直接ds.GetXML()      
            }

3、利用XmlSerializer來將類的屬性值轉換為XML檔案的元素值。

用一個字串作為一個XML檔案中的xmlAttribute或xmlElement。[其元素或屬性由類的定義來設定(xml序列化)]

using System;System.xml.Serialization;

先初始化一個類,設定屬性值

var xmlDoc = new XmlDocument();
//Create the xml declaration first
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
//Create the root node and append into doc
var el = xmlDoc.CreateElement("Contacts");
xmlDoc.AppendChild(el);
// Contact
XmlElement elementContact = xmlDoc.CreateElement("Contact");
XmlAttribute attrID = xmlDoc.CreateAttribute("id");
attrID.Value = "01";
elementContact.Attributes.Append(attrID);
el.AppendChild(elementContact);
// Contact Name
XmlElement elementName = xmlDoc.CreateElement("Name");
elementName.InnerText = "Daisy Abbey";
elementContact.AppendChild(elementName);
// Contact Gender
XmlElement elementGender = xmlDoc.CreateElement("Gender");
elementGender.InnerText = "female";
elementContact.AppendChild(elementGender);
xmlDoc.Save("test1.xml");

建XmlSerializer範例

class XXX {  
               XmlSerializer ser = new XmlSerializer(Type.GetType("forxml.truck"));   
               Truck tr = new Truck();     
               tr.ID = 1;    
               tr.cheID = "贛A T34923";
           }

Serialize方法–完成對類的序列化

XmlTextWriter xtw = new XmlTextWriter("myxml.xml",Encoding.UTF8); 

        用XmlTextWriter 建立一個XML檔案   
         ser.Serialize(xtw, tr);      
         //如果只想顯示,可以直接ser.Serialize(Console.Out, tr);
}

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);

範例:寫入xml

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檔案如下:

<?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");
}

執行結果:

<?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 DeleteNode()
{
    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load("D:\book1.xml");
    XmlNodeList xnl = xmlDocument.SelectSingleNode("Employees").ChildNodes;

    foreach (XmlNode xn in xnl)
    {
 if (xn.Name == "Node")
 {
     XmlElement xe = (XmlElement)xn;//將xn的屬性轉換為XmlElement
     xe.RemoveAttribute("ID");//移除xe的ID屬性
     XmlNodeList xnl2 = xe.ChildNodes;
     for (int i = 0; i < xnl2.Count; i++)
     {
  XmlElement xe2 = (XmlElement)xnl2.Item(i);
  if (xe2.Name == "title")
  {
      xe.RemoveChild(xe2);//刪除節點title
  }
     }
 }
    }
    xmlDocument.Save("D:\book3.xml");
}

結果:

<?xml version="1.0" encoding="GB2312"?>
-<Employees>
-<Node ISB="2-3631-4" Name="薪薪">-<price>
<weight>20</weight>
</price>
</Node>-
<Node2 Name="張三">
<title>心情好</title>
</Node2>-
<Node2 Name="張三">
<title>心情好</title>
</Node2>
</Employees>

c#讀取xml檔案

xml檔案如下:

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

在寫入xml檔案時,最主要使用了兩個方法: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);
        }
}

總結

到此這篇關於C#讀寫xml檔案方法的文章就介紹到這了,更多相關C#讀寫xml檔案內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com