处理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
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingMSXML2;
namespaceMSXMLTest
{
publicpartialclassForm1:Form
{
privateDOMDocument60doc;
publicForm1()
{
InitializeComponent();
}
privatevoidlistBox1_SelectedIndexChanged(objectsender,EventArgse)
{
stringsrch =this.listBox1.SelectedItem.ToString();
IXMLDOMNodend = doc.selectSingleNode("bookstore/book[@ISBN= '"+srch+"']");
//选择所有ISBM=srch并且父结点等于bookstore的所有book接点
MessageBox.Show(nd.text);
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
doc =newDOMDocument60();
doc.load(@"D:\books.xml");
IXMLDOMNodeListnodes;
nodes = doc.selectNodes("bookstore/book");
IXMLDOMNodenode = nodes.nextNode();
while(node !=null)
{
this.listBox1.Items.Add(node.attributes.getNamedItem("ISBN").text);
node = nodes.nextNode();
}
}
}
}
◆ 使用System.XML
使用XmlTextReader类
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Xml;
namespaceXmlTextReaderTest
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidbutton1_Click(objectsender,EventArgse)
{
System.Xml.XmlTextReaderxr =newSystem.Xml.XmlTextReader(@"D:\books.xml");
while(xr.Read())
{
if(xr.NodeType ==XmlNodeType.Text)
this.listBox1.Items.Add(xr.Value);
}
}
privatevoidlistBox1_SelectedIndexChanged(objectsender,EventArgse)
{
stringstr =this.listBox1.SelectedItem.ToString();
MessageBox.Show(str);
}
}
}