XML 文档对象模型---- 将XML与XmlDocument (w3c DOM) 一起保存

如何使用 XmlDocument (W3C DOM) 保存 XML

此示例阐释如何使用 XmlDocument 类更新和保存 XML,该类是 WWW 联合会 (W3C) 文档对象模型 (DOM) 的实现。

此示例是如何加载和使用 XmlDocument 主题的继续。

 
VB SaveXmlDocument.aspx

[ 运行示例] | [ 查看源代码]

XmlDocument 类的 Save 方法使 XmlDocument 能够将 XML 数据保存到文件、流和 XmlWriter。

该示例应用程序(如下面的代码所示)在文件 books.xml 中浏览,以将所有书籍的价格增加 2%。然后,该应用程序将 XML 保存到一个名为 updatebooks.xml 的新文件。

public void Run(String[] args)

            {

            try

            {

            // Create XmlDocument and load the XML from file

            XmlDocument myXmlDocument = new XmlDocument();

            myXmlDocument.Load (new XmlTextReader (args[0]));

            Console.WriteLine ("XmlDocument loaded with XML data successfully ...");

            Console.WriteLine();

            IncreasePrice(myXmlDocument.DocumentElement);

            // Write out data as XML

            myXmlDocument.Save(args[1]);

            Console.WriteLine();

            Console.WriteLine("Updated prices saved in file {0}", args[1]);

            }

            catch (Exception e)

            {

            Console.WriteLine ("Exception: {0}", e.ToString());

            }

            }

            
C# VB  

IncreasePrice 方法使用 XmlNode 类的 FirstChild 方法递归地重复 XML 文档,以沿着树向下移。如果没有子节点,则此方法返回一个空值。NextSibling 属性移到紧靠在当前节点旁的节点,如果没有节点可移动,则返回一个空值。每当应用程序找到一个名为价格的节点时,它就更新该价格。下列代码显示 IncreasePrice 方法的操作原理。

public void IncreasePrice(XmlNode node)

            {

            if (node.Name == "price")

            {

            node = node.FirstChild;

            Decimal price = Decimal.Parse(node.Value);

            // Increase all the book prices by 2%

            String newprice = ((Decimal)price*(new Decimal(1.02))).ToString("#.00");

            Console.WriteLine("Old Price = " + node.Value + "\tNew price = " + newprice);

            node.Value = newprice;

            }

            node = node.FirstChild;

            while (node != null)

            {

            IncreasePrice(node);

            node = node.NextSibling;

            }

            }

            
C# VB  
XmlDocument loaded with XML data successfully ...

Old Price = 8.99        New price = 9.17

Old Price = 11.99       New price = 12.23

Old Price = 9.99        New price = 10.19

Updated prices saved in file updatebooks.xml

摘要

  1. XmlDocument 类可将 XML 保存到文件、流或 XmlWriter。
  2. XmlNode 类使您可以在 XML 文档中浏览并修改其中的节点。

你可能感兴趣的:(document)