处理XML
◆ System.Xml命名空间
类名 |
说明 |
XMLReader |
抽象类,提供快速的没有缓存的XML数据,只向前的。 |
XMLWriter |
抽象类,以流或文件的方式提供快速的,没有缓存的XML数据 |
XMLTextReader |
扩展XMLReader, 提供访问XML数据的只读向前流。 |
XMLTextWriter |
扩展XMLWriter, 快速生成只向前的XML 流。 |
XMLNode |
抽象类,表示XML 文档的一个结点 |
XMLDocument |
扩展XMLNode, 给出XML文档在内存中的树形表示。 |
XMLDataDocument |
扩展XMLDataDocument, 可以从XML数据中加载文档, 也可以从ADO.NET中加载文档,允许放在一个视图中。 |
XMLResolver |
抽象类, 分析基于XML的外部资源,例如DTD和模式引用,也可以用于处理<xsl:include>和<xls:import> |
XMLUrlResolver |
扩展XMLUrlResolver, 用URL解析外部资源。 |
◆ 在.NET中使用MSXML
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSXML2;
namespace MSXMLTest
{
public partial class Form1 : Form
{
private DOMDocument60 doc;
public Form1()
{
InitializeComponent();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string srch = this.listBox1.SelectedItem.ToString();
IXMLDOMNode nd = doc.selectSingleNode("bookstore/book[@ISBN= '"+srch+"']");
//选择所有ISBM=srch并且父结点等于bookstore的所有book接点
MessageBox.Show(nd.text);
}
private void button1_Click(object sender, EventArgs e)
{
doc = new DOMDocument60();
doc.load(@"D:\books.xml");
IXMLDOMNodeList nodes;
nodes = doc.selectNodes("bookstore/book");
IXMLDOMNode node = nodes.nextNode();
while (node != null)
{
this.listBox1.Items.Add(node.attributes.getNamedItem("ISBN").text);
node = nodes.nextNode();
}
}
}
}
◆ 使用System.XML
使用XmlTextReader类
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace XmlTextReaderTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(@"D:\books.xml");
while (xr.Read())
{
if (xr.NodeType == XmlNodeType.Text)
this.listBox1.Items.Add(xr.Value);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string str = this.listBox1.SelectedItem.ToString();
MessageBox.Show(str);
}
}
}