曾经爱晚人








永远自由的心

[转]XML初级应用ABC

在.NET中使用XML

  如果使用过MSXML3,那么在.NET应用程序中使用XML将是一个相当简单的过程。即时没有接触过MSXML3,也不要紧,你会发现使用.NET平台提供的相关类也是很容易的一件事情。
  有两种主要API可用于访问建立在XML文档中的数据,它们包括只向前的无缓冲存取以及随机存取,而且自始至终都使用到文档对象模型DOM。有关这2个API的类位于System.XML集合中。
 
  如果要快速有效地访问XML文档中的数据,就需要使用XmlTextReader类。这个类采取“拉”模式处理方式,要比简单XML API(SAX)中的“推”模式处理方式优越许多。使用XmlTextReader类之前首先要引用System.Xml集合,在C#中是使用“using”关键字来引用,在Visual Basic中则是使用“imports”关键字。引用了集合后,就可以象下面的代码所示开始例示读操作了:
XmlTextReader reader = new XmlTextReader(pathToXmlDoc);
int elementCount = 0;
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
elementCount++;
}

  XmlTextReader类中有几个不同的构造器,上面所示的负责接收一个XML文件的路径作为字符串参数。
  虽然只向前的“拉”模式处理相当有效率,但它却是只读的,所以不能允许执行插入、删除或者更新XML文档节点的操作。当需要对XML文档施加更多的控制并需要更大的灵活性时,我们可以看一看文档对象模型DOM。DOM API的功能将XML文档中的每一个节点装载到一个树形结构中,看起来就象是一个“家谱”。内存中有了这个结构,随机存取XML文档中的不同节点就变得可行。
  开始创建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集合中还有多种其他类可用于执行不同的任务。上面的介绍仅仅是浅尝则止,大量的应用还需要更多的练习。

  读取XML文件
  下面介绍如何使用XmlTextReader类读取XML文档,并将数据显示输出。
  System.XML名称空间中定义了两个类-XmlReader与XmlTextReader,其中XmlTextReader类来源于XmlReader类,而XmlTextReader类就可以用于读取XML文档,这个文档的Read函数将读取文档内容,直到节点尾部。
  以下是具体的实现步骤:

  1、引用名称空间
  因为相关XML的类是在System.XML名称空间中定义的,所以第一件事情就是引用这个名称空间:
using System.Xml;
  2、打开XML文档
  XmlTextReader类的构造器可用于打开一个XML文件。本例程的XML文件叫做xmltest.xml,位于C:\temp目录下。打开文件c:\temp\xmltest.xml的命令如下:
XmlTextReader reader = new XmlTextReader("C:\\temp\\xmltest.xml");

  3、读取数据
  读取XML文件的数据,可以使用XmlTextReader类的Read方法:
while ( reader.Read() )
{
Console.WriteLine(reader.Name);
}

  4、完整执行代码readxml.cs

 

namespace WriteToXML
{
using System;
using System.Xml;
/// <summary>
/// Summary description for Class1.
/// </summary>

public class Class1
{
public Class1()
{

}
 
public static int Main(string[] args)
{
try
{
XmlTextWriter writer 
= new XmlTextWriter("C:\\temp\\xmltest.xml"null);
writer.WriteStartDocument();
writer.WriteComment(
"Commentss: XmlWriter Test Program");
writer.WriteProcessingInstruction(
"Instruction","Person Record");
writer.WriteStartElement(
"p""person""urn:person");
writer.WriteStartElement(
"LastName","");
writer.WriteString(
"Chand");
writer.WriteEndElement();
writer.WriteStartElement(
"FirstName","");
writer.WriteString(
"Chand");
writer.WriteEndElement();
writer.WriteElementInt16(
"age",""25);
writer.WriteEndDocument(); 
}

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


return 0;
}

}

}


 

  插入数据到XML文档中
  要实现将XML数据插入到一个现存文档或者一个新文档中的目的,可以使用XmlNode类和XmlDocument类。具体的实现步骤如下:

  1、引用名称空间
  因为相关XML的类是在System.XML名称空间中定义的,所以第一件事情就是引用这个名称空间:
using System.Xml;

  2、装载XML到文档中
  我们可以使用XmlDocument的LoadXml方法将XML数据装载到一个文档中,或者是装载一个现存的XML文档。下面的代码装载XML数据到文档中:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<XMLFile>" +

" <SomeData>Old Data</SomeData>" +
"</XMLFile>");
 

  3、插入XML数据
  下面的代码将XML数据插入到文件中,然后保存为InsertedDoc.xml:

 

try 

XmlNode currNode; 
XmlDocument doc 
= new XmlDocument(); 
doc.LoadXml(
"<XMLFile>" + 
" <SomeData>Old Data</SomeData>" + 
"</XMLFile>"); 
XmlDocumentFragment docFrag 
= doc.CreateDocumentFragment(); 
docFrag.InnerXml
="<Inserted>" + 
" <NewData>Inserted Data</NewData>" + 
"</Inserted>"
// insert the availability node into the document 
currNode = doc.DocumentElement.FirstChild; 
currNode.InsertAfter(docFrag, currNode.LastChild); 
//save the output to a file 
doc.Save("InsertedDoc.xml"); 
}

catch (Exception e) 

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

 

  代码执行后,新文档的内容如下:
- <XMLFile>
- <SomeData>
Old Data
- <Inserted>
<NewData>Inserted Data</NewData>
</Inserted>
</SomeData>
</XMLFile>

posted on 2005-10-11 18:35  e旋风  阅读(897)  评论(0编辑  收藏  举报

导航