ASP.NET利用xpath來取得單一(SelectSingleNode)或多個(SelectNodes)xml node的運用
假設有一個xml檔內容如下..
<?xml version="1.0" encoding="utf-8" ?>
<A>
<B>
<C c1="東京">JAPAN</C>
</B>
<B>
<C c1="台北">TAIWAN</C>
<C c1="台南">TAIWAN</C>
</B>
<B>
<C c1="北京">CHINA</C>
</B>
</A>
要如何取出xml檔某結點裡的內容或屬性內容....下面有一個簡單的範例..使用xpath作法...
asp.net(c#)部分程式碼
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
public partial class XPATH : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("XML.xml"));//載入xml檔
string xPathExpression1 = "/A/B/C[.='TAIWAN']";//找node裡有'TAIWAN'
XmlNodeList nodelist = xmldoc.SelectNodes(xPathExpression1);//multi node
string xPathExpression2 = "/A/B/C[@c1='台北']";//找node屬性有'台北'
XmlNode node = xmldoc.SelectSingleNode(xPathExpression2);//single node
//輸出結果:TAIWAN
Response.Write(node.OuterXml);
Response.Write("<p>");
//輸出結果:台北台南
foreach (XmlNode item in nodelist)
{
Response.Write(item.Attributes["c1"].Value);
Response.Write("<br/" + ">");
}
}
}
執行結果: