ASP.NET利用xpath來取得單一(SelectSingleNode)或多個(SelectNodes)xml node的運用

來源:互聯網
上載者:User

假設有一個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/" + ">");
}
}
}

   

 

執行結果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.