.NET中XML的常用操作_转摘

1         系统类的介绍

1.1       XmlDocument (DOM)

Xml整个读入内存中,操作方便,不适宜读取大文本。

命名空间: System.Xml

1.2       XmlReader (SAX)

不加载文本到内存,直接读取文本,内存占用低,可以快速读取文件中的指定节点。

命名空间: System.Xml

1.3       XmlSchema

Xml架构,用于验证Xml文本的有效性。

命名空间: System.Xml.Schema

2         典型应用示例

2.1       XmlDocument

// 新建一个XmlDocument对象

XmlDocument oXmlDocument 
= new XmlDocument();

// oXmlDocument.Load(filename); // 读取整个文件

 

// 添加 XML 文件声明

XmlDeclaration xmlDeclaration 
= oXmlDocument.CreateXmlDeclaration(XmlVersion, XmlEncoding, null);

oXmlDocument.AppendChild(xmlDeclaration);

 

// 添加 POWER_EXCHANGE 根节点

XmlElement root 
= oXmlDocument.CreateElement("POWER_EXCHANGE");

root.SetAttribute(
"xmlns:xsi""http://www.w3.org/2001/XMLSchema-instance");

root.SetAttribute(
"xsi:noNamespaceSchemaLocation""exchange.xsd");

oXmlDocument.AppendChild(root);

2.2       XmlReader

//从文件读取
XmlReader read = XmlReader.Create(filename);

read.ReadToFollowing(
"OBJECT");

string sName = xread.GetAttribute("NAME");

string sVerb = xread.GetAttribute("VERB");


//从Xml字符串读取
StringReader sReader = new StringReader(sXml);

XmlReader xmlReader 
= XmlReader.Create(sReader);

read.ReadToFollowing(
"OBJECT");

string sName = xread.GetAttribute("NAME");

string sVerb = xread.GetAttribute("VERB");

2.3       XmlSchema

// Create a schema validating XmlReader.

XmlReaderSettings settings 
= new XmlReaderSettings();

settings.Schemas.Add(targetNamespace, xsdFile);

settings.ValidationEventHandler 
+= new ValidationEventHandler(ValidationEventHandler);

settings.ValidationFlags 
= settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;

settings.ValidationType 
= ValidationType.Schema;

 

XmlReader reader 
= XmlReader.Create(xmlFile, settings);

 

// The XmlDocument validates the XML document contained

// in the XmlReader as it is loaded into the DOM.

XmlDocument document 
= new XmlDocument();

document.Load(reader);

posted on 2006-12-13 16:13    阅读(328)  评论(0编辑  收藏  举报

导航