通常看到以下這種XML具有xmlns的NameSpace設定時,常常用

SelectNodes或SelectSingleNode都會選到奇怪的Node,或是選不到

 

<feed xmlns='http://www.w3.org/2005/Atom' xmlns:exif='http://schemas.google.com/photos/exif/2007' xmlns:gphoto='http://schemas.google.com/photos/2007' xmlns:media='http://search.yahoo.com/mrss/' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/'>

<entry>

<media:group>

<media:content url='http://www.google.com'></media:content>
<media:thumbnail url='http://welkingunther.pixnet.net'></media:thumbnail>

</media:group>

<summary>威爾金‧貢特爾</summary>

</entry>

</feed>

 

 

XmlDocument xd = new XmlDocument();                    

xd.Load("XML的路徑");

XmlNamespaceManager nsManager = new XmlNamespaceManager(xd.NameTable);              

nsManager.AddNamespace("atom", "http://www.w3.org/2005/Atom");               

nsManager.AddNamespace("media", "http://search.yahoo.com/mrss/");   

 

//兩條斜線是相對的去選,一條斜線是從根開始去選,沒有斜線是從目前的Node之下去選         

XmlNodeList NodeList = xd.SelectNodes("//atom:entry",nsManager);          

foreach (XmlNode everyNode in NodeList)

{

    //這些SelectSingleNode裡面的開頭就是沒有斜線去選

    string myContent= everyNode.SelectSingleNode("media:group/media:content", nsManager).Attributes.GetNamedItem("url").Value

    string myThumbnail= everyNode.SelectSingleNode("media:group/media:thumbnail", nsManager).Attributes.GetNamedItem("url").Value

    string mySummary= everyNode.SelectSingleNode("atom:summary", nsManager).InnerText             

);                   

welkingunther 發表在 痞客邦 PIXNET 留言(0) 人氣()