• C#如何读写XML文件?
  • 发布于 2个月前
  • 188 热度
    0 评论
C#读写xml文档主要通过XmlDocument、XmlReader和XmlWriter三个类实现。
1.XmlReader只有读功能。
2.XmlWriter只有写功能。
3.XmlDocument既有读也有写的功能。

读(Read)
本篇文章,读取的xml文档为在线xml文档(非本地文件,换成本地文档也行),可以用浏览器打开这个文档地址:https://www.duidaima.com/sitemap.xml查看文档内容。下面,我们读取这个文档内容。有以下两种方式。

使用XmlReader读取文件
按照如下代码示例,可以读取任意xml文档(本地文件或者远程服务器上的文件)。
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)
        {
            // 堆代码 duidaima.com
            //使用静态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();
        }
    }
}
使用XmlDocument读取文件
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)
1.使用XmlWriter写内容至文档
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();
        }
    }
}

2.使用XmlDocument向xml文档写内容
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");
        }
    }
}
(完)
用户评论