正在阅读:从基本应用实例快速步入XML编程世界从基本应用实例快速步入XML编程世界

2005-09-21 10:10 出处: 作者:北国蓑衣 责任编辑:moningfeng

  开始创建DOM树形结构前,首先引用System.Xml集合,然后例示XmlDocument类:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathToXmlDoc);
XmlNode root = xmlDoc.DocumentElement;


  通过使用XmlDocument类中的相关方法,在树形结构中添加节点的操作可以很容易地完成。下面的例子演示了如何从一个文件中装载XML,然后在根节点root下添加一个子元素以及它的相关属性:

XmlDocument xmlDoc = new XmlDocument();
XmlDoc.Load(pathToXmlDoc);
XmlElement root = xmlDoc.DocumentElement;
XmlElement newNode = doc.CreateElement("newNode");
newNode.SetAttribute("id","1");
root.AppendChild(newNode);


  以上代码执行后,将产生下面的XML文档:

<?xml version="1.0"?>
<root>
<newNode id="1"/>
</root>


  当需要将包含XML的字符串装载进DOM中时,可以使用XmlDocument类的LoadXml()方法。装载进去后,就可以按照下面的方式操作XML:

string myXml = "<root><someNode>Hello</someNode></root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(myXml);
//....manipulation or reading of the nodes can occur here


  除了以上几种,在System.Xml集合中还有多种其他类可用于执行不同的任务。上面的介绍仅仅是浅尝则止,大量的应用还需要更多的练习。

键盘也能翻页,试试“← →”键

关注我们

最新资讯离线随时看 聊天吐槽赢奖品