C# read and write xml documents mainly through XmlDocument, XmlReader and XmlWriter three classes to achieve.

XmlReader only has read functionality.

XmlWriter has only write functionality.

XmlDocument has both Read and Write functionality.

Read

This article, read the xml document for the online xml document (non-local files, replaced by local documents can also be), you can use your browser to open this document address: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml to view the contents of the document.

Here, we read the contents of this document.

There are the following two ways.

Use XmlReader to read the file

According to the following code example, you can read any xml document (local file or a file on a remote server).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;//为了支持XmlReader,必须包含Xml命名空间。

namespace ParsingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用静态Create()方法,创建一个XmlReader对象。该方法有多个重载,我们使用最简单的,用指向文档的URL。
            XmlReader xmlReader = XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
            //只要有内容读取,loop中循环条件就一直为真。
            while (xmlReader.Read())//Read()方法,读取下一个节点,如果成功读取了下一个节点就返回true。
            {
                //NodeType获取当前节点类型, Name获取当前节点限定名。
                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "Cube"))
                {
                    //HasArrtibutes返回结果:如果当前节点具有属性,则为 true;否则为 false。
                    //GetAttribute(string name)返回指定属性的值,如果未找到,返回null。
                    if (xmlReader.HasAttributes)
                        Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
                }
            }
            Console.ReadKey();
        }
    }
}

Reading documents using XmlDocument

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace ParsingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml";);
            //DocumentElement表示文档的根节点,如果没有则返回null。ChildNodes获取当前节点所有子节点
            foreach (XmlNode xmlNode in xmlDoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes)
                Console.WriteLine(xmlNode.Attributes["currency"].Value + ": " + xmlNode.Attributes["rate"].Value);
            Console.ReadKey();
        }
    }
}

Write

Use XmlWriter to write content to a document

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;
using System.Text;
using System.Xml;
namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            // 向磁盘【C:\Users\a\Desktop\test.xml】文件写入。
            XmlWriter xmlWriter = XmlWriter.Create(@"C:\Users\a\Desktop\test.xml");

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("users");
            //添加一个element
            xmlWriter.WriteStartElement("user");
            //添加attribute
            xmlWriter.WriteAttributeString("age", "42");
            //添加innerText
            xmlWriter.WriteString("John Doe");
            //结束编写第一个element
            xmlWriter.WriteEndElement();
            //开始另一个element
            xmlWriter.WriteStartElement("user");
            xmlWriter.WriteAttributeString("age", "39");
            xmlWriter.WriteString("Jane Doe");

            //结束编写文档
            xmlWriter.WriteEndDocument();
            //关闭流
            xmlWriter.Close();
        }
    }
}

Use XmlDocument to write content to xml documents

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace WritingXml
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlNode rootNode = xmlDoc.CreateElement("users");
             //将指定的节点添加到该节点的子节点列表的末尾。
            xmlDoc.AppendChild(rootNode);
            XmlNode userNode = xmlDoc.CreateElement("user");
            XmlAttribute attribute = xmlDoc.CreateAttribute("age");
            attribute.Value = "42";
            //为userNode添加属性
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "John Doe";
            //为rootNode添加子节点。    
            rootNode.AppendChild(userNode);
            userNode = xmlDoc.CreateElement("user");
            attribute = xmlDoc.CreateAttribute("age");
            attribute.Value = "39";
            userNode.Attributes.Append(attribute);
            userNode.InnerText = "Jane Doe";
            rootNode.AppendChild(userNode);

            // 将内容保存至【C:\Users\a\Desktop\test-doc.xml】                      
            xmlDoc.Save(@"C:\Users\a\Desktop\test-doc.xml");
        }
    }
}