2016-11-01 78 views
0

我想解析來自REST調用的XML響應。我可以用我的流式閱讀器閱讀XML,但是當我嘗試選擇第一個節點時,它什麼都沒帶回來。下面是我的XML:閱讀XML節點列表

<?xml version="1.0" encoding="UTF-8" standalone="true"?>  
<slot_meta_data xmlns:ns2="http://www.w3.org/2005/Atom">  
    <product id="MDP">  
     <name>MDP</name>  
    </product>   
    <product id="CTxP">  
     <name>CTxP</name>  
    </product>  
    <product id="STR">  
     <name>STR</name>  
    </product>  
    <product id="ApP">  
     <name>ApP</name> 
     <slot>  
      <agent_id>-1111</agent_id>  
      <agent_name>ApP</agent_name>  
      <index_id>-1</index_id>   
      <alias>App Alias</slot_alias>  
     </slot>  
    </product>   
    <product id="TxP">  
     <name>TxP</name>   
     <slot>  
      <agent_id>2222</agent_id>  
      <agent_name>App2</agent_name>  
      <index_id>-1</index_id>  
      <alias>App2 Alias</slot_alias>  
     </slot>  
    </product>  
</slot_meta_data> 

這裏是我的代碼

string newURL = "RESTURL"; 

HttpWebRequest request = WebRequest.Create(newURL) as HttpWebRequest; 
HttpWebResponse response = request.GetResponse() as HttpWebResponse; 

StreamReader reader = new StreamReader(response.GetResponseStream()); 

XmlDocument xdoc = new XmlDocument(); 
xdoc.Load(response.GetResponseStream()); 

XmlNodeList list = xdoc.SelectNodes("/slot_meta_data[@*]"); 

foreach (XmlNode node in list) 
{ 
    XmlNode product = node.SelectSingleNode("product"); 
    string name = product["name"].InnerText; 
    string id = product["id"].InnerText; 

    Console.WriteLine(name); 
    Console.WriteLine(id); 
    Console.ReadLine(); 
} 

當調試列表中,它具有0

+0

有'slot_meta_data'元素沒有屬性......只是一個名稱空間聲明。 –

回答

1

計數使用XML LINQ

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 


namespace ConsoleApplication22 
{ 
    class Program 
    { 
     const string FILENAME = @"c:\TEMP\TEST.XML"; 
     static void Main(string[] args) 
     { 

      XDocument doc = XDocument.Load(FILENAME); 

      var results = doc.Descendants("product").Select(x => new { 
       name = (string)x.Element("name"), 
       slot = x.Elements("slot").Select(y => new { 
        agent_id = (int)y.Element("agent_id"), 
        agent_name = (string)y.Element("agent_name"), 
        index_id = (int)y.Element("index_id"), 
        slot_alias = (string)y.Element("slot_alias") 
       }).FirstOrDefault() 
      }).ToList(); 

     } 

    } 

} 
+0

謝謝。這很好。所以我試圖把它包裝到一個foreach循環中以逐一獲取它們。我可以得到產品屬性(foreach(var result in results)),但是當我嘗試獲取插槽屬性時,我將「對象未設置爲對象的實例」。我正在使用int agent_id = result.slot.agent_id – maltman

+0

您不需要包裝在for循環中。只需在Linq之後枚舉for循環中的變量結果即可。並非所有xml文件中的產品都有插槽。前三款產品沒有插槽,只有最後兩款。 – jdweng

+0

所以我添加了一個if來檢查slot = null。然後在其他地方我添加了另一個foreach循環插槽。這可以嗎? – maltman