TOC

This article is currently in the process of being translated into Chinese (~45% done).

XML:

Writing XML with the XmlDocument class

上一章介绍了使用XmlWriter类写XML文件。不过,在某些情况下,尤其在更新现有的XML文档时,使用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.Attributes.Append(attribute);
            userNode.InnerText = "John Doe";
            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);

            xmlDoc.Save("test-doc.xml");
        }
    }
}

上述代码生成的XML为:

<users>
  <user age="42">John Doe</user>
  <user age="39">Jane Doe</user>
</users>

以上示例显然比使用XmlWriter类更加面向对象一些,所需代码量也多一些。此方法为,实例化一个XmlDocument对象,以作为生成新的element和attribute对象的基础,通过其CreateElement()和CreateAttribute()方法。每次操作都把新生成的element要么直接添加到文档,要么添加到另一个element上。示例中展示了这个过程,根节点(“users”)被直接添加到文档中,而两个user节点被添加到根节点上。属性(attribute)当然是被添加到其所属的element上,使用其Attributes属性的Append()方法。整个XML文档在最后一行代码被使用Save()方法写入磁盘。

虽然此方法如前面所述,需要比使用XmlWriter类时多一些代码才能实现,但想象一下,如果只需要打开一个现有XML文档,做一些小修改。使用XmlWriter类来实现时,必需先用XmlReader类读取整个文档,保存在内存中,进行修改,然后再把全部内容通过XmlWriter类写回到文件。因为XmlDocument类自动完成了在内存中保存所有内容的操作,更新一个现有的XML文件就变得非常简单。下面的示例打开在上一章中生成的“test-doc.xml”文件,把每个user的age值加1。看下实现起来多简单:

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();
            xmlDoc.Load("test-doc.xml");
            XmlNodeList userNodes = xmlDoc.SelectNodes("//users/user");
            foreach(XmlNode userNode in userNodes)
            {
                int age = int.Parse(userNode.Attributes["age"].Value);
                userNode.Attributes["age"].Value = (age + 1).ToString();
            }
            xmlDoc.Save("test-doc.xml");           
        }
    }
}

本示例先加载XML文件,然后查找所有的<user>节点。然后循环迭代这些节点,读取每个节点的age属性,解析为整数值,把此值加1后再写回到此节点的原属性上。最后把文档保存回同一文件,打开文件看看,所有user都过了个生日(年龄增长了一岁)。很酷吧!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!