.net下對具有名稱空間的XML使用XPath的方法

來源:互聯網
上載者:User
xml

   這兩天都在對一個其他公司提供的RSS介面進行編程,由於他們RSS提供的是1.0版本,其中的XML部分是有名稱空間的,為此這一兩天為了這個,摔了很多跟頭,Unicode 編碼的問題,XPath 的問題,XSLT 解析的問題。下面把這些問題的解決方案羅列出來,方便後來者。

        使用 XPath 的問題: 由於存在名稱空間,你的XPath需要額外的通過 XmlNamespaceManager 類進行一些設定。這個方法是我在:http://www.error-bank.com/microsoft.public.dotnet.xml__35_R5x1v5$DHA.2040@TK2MSFTNGP12.phx.gbl_Thread.aspx 看到的,那裡對這個問題的解決是:

Oleg Tkachenko [XML MVP, XmlInsider]
http://blog.tkachenko.com

解決的。非常感謝他在那裡回答,讓我找到瞭解決方法。下面是我的一個範例程式碼:

string ww = @"<item rdf:about=""http://ncsp.forum.nokia.com/download/?asset_id=10357""
xmlns:rdf=""http://www.w3.org/1999/02/22-rdf-syntax-ns#""
xmlns: dc=""http://purl.org/dc/elements/1.1/""
xmlns:ncsp=""http://ncsp.forum.nokia.com/"">
 <title>Advanced Audio Support v1.0</title>
<link>http://ncsp.forum.nokia.com/download/?asset_id=10357</link>
 <description>Media Server Audio Streaming plug-in installation file for Nokia 9200 Series Communicators. Deprecated - use the official audio stream plug-in instead, available from SDK v1.2 and later.</description>
 <dc:title xmlns: dc=""http://purl.org/dc/elements/1.1/"">Advanced Audio Support v1.0</dc:title>
 <dc:identifier xmlns: dc=""http://purl.org/dc/elements/1.1/"">10357</dc:identifier>
 <dc:language xmlns: dc=""http://purl.org/dc/elements/1.1/"">English</dc:language>
 <ncsp:filesize xmlns:ncsp=""http://ncsp.forum.nokia.com/"">7 kB</ncsp:filesize>
 <ncsp:class xmlns:ncsp=""http://ncsp.forum.nokia.com/"">Toolkit</ncsp:class>
</item>";
XmlReader read = new XmlTextReader(new StringReader(ww));
XPathDocument doc = new XPathDocument(read);
XPathNavigator nav = doc.CreateNavigator();
string strXPath = "/item/dc:identifier";
XPathExpression expr = nav.Compile(strXPath);
XmlNamespaceManager mngr = new XmlNamespaceManager(nav.NameTable);
mngr.AddNamespace("dc","http://purl.org/dc/elements/1.1/");
mngr.AddNamespace("ncsp","http://ncsp.forum.nokia.com/");
expr.SetContext(mngr);
XPathNodeIterator iter = nav.Select(expr);
string strVal = null;
if (iter.MoveNext()){
      strVal = iter.Current.Value;
}

XML+XSLT 解析的問題,出這個問題,最後發現是在XML的頭上,多定義了一個名稱空間造成的,刪除這個名稱空間就可以了。由於這些RSS,是其他公司提供的,害的我找自己的問題,找了很久。

 



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.