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);
}
}
}