1、XML 文档对象模型(DOM) 类是XML 文档的内存中表示形式,它在内存中表示是常见的结构化方法,尽管实际的XML 数据在文件中时或从另一个对象传入时以线性方式存储。 主要执行DOM 查询类和方法如下:
• XmlNode 方法
– SelectNodes()
– SelectSingleNode()
• XmlDocument 方法
– GetElementsByTagName()
– GetElementById()
2、XPath
创建XPathNavigator 对象,可以使用CreateNavigator 方法返回XPathNavigator 对象XPathDocument、XmlDocument、XmlNode
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.Data.SqlClient;
using System.Xml;
using System.Xml.XPath;
namespace UsingDataSet
{
public partial class Form1 : Form
{
string strSQL = null;
DataSet ds = null;
public Form1()
{
InitializeComponent();
}
private void readToolStripMenuItem_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Study\XmlControl\UsingXml\Books.xml");
XmlNode node = doc.DocumentElement;
foreach (XmlNode xn in node)
{
MessageBox.Show(xn.ChildNodes[0].Name + ":"+xn.ChildNodes[0].InnerText);
}
}
//SelectNodes
private void conditToolStripMenuItem_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
//doc.Load(@"D:\Study\XmlControl\UsingXml\ProductXmlXPath.Xml");
//XmlNodeList nodes = doc.SelectNodes("/Products/Category/ProductName[../ProductID<=2]");
//ProductXmlXPath.xml 显示ProductName根据条件ProductID<=2进行选择
doc.Load(@"D:\Study\XmlControl\UsingXml\ProductXmlAuto.xml");
XmlNodeList nodes = doc.SelectNodes("/Products/Product/@ProductName[../@ProductID<=2]");
foreach (XmlNode xn in nodes)
{
MessageBox.Show(xn.ChildNodes[0].Name + ":" + xn.ChildNodes[0].InnerText);
}
}
//XPathNavigator
private void getXmlToolStripMenuItem1_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Study\XmlControl\UsingXml\ProductXmlXPath.Xml");
XPathNavigator nav = doc.CreateNavigator();
//XPathNodeIterator iter = nav.Select("/Products/Category/ProductName[../ProductID<=2]");
//foreach(XmlNode xn in iter)
MessageBox.Show(nav.OuterXml);
}
}
}