循环返回XML Result并分配值

时间:2015-01-07 00:10:19

标签: c# xml xmlnode

我正在调用外部MVC控制器并传入两个传递XML结果的参数我现在这样做的方式如下,请注意我的XML经验几乎为0

 try
     {
         var url = ConfigurationManager.AppSettings["url"] + String.Format("/ws/RetailerBrandsFiltered?postcode={0}&countryCode={1}", model.Postcode, model.SelectedCountry);

         // Create the request to call the external mvc controller to retrieve the retailers
         var req = (HttpWebRequest)WebRequest.Create(url);
         req.Method = "GET";
         req.ContentType = "xml";

         // Do the request to external controller
         var stIn = new StreamReader(req.GetResponse().GetResponseStream());
         var responce = stIn.ReadToEnd();

         foreach (var item in responce)
         {
             string urn = item["URN"].InnerText
         }

     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }

我正在尝试遍历响应并获取XML节点并将它们分配给模型(我尚未实现)但是为了测试我试图获取第一个值并将其分配给字符串。

哪个不能正常工作消息是无法应用索引来键入char,理想情况下我的for循环看起来像这样。

 foreach (var item in responce)
 {
     string urn = item["URN"].InnerText;
     string name = item["NAME"].InnerText;
     string address = item["ADDRESS"].InnerText;
 }

一旦这个工作,我将用模型绑定替换字符串。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

变量reponce是一个字符串,当你尝试迭代它时,你隐式地将字符串转换为char[]并迭代它。

将流加载到XDocument并使用Linq获取值:

try
{
     var url = ConfigurationManager.AppSettings["url"] + string.Format("/ws/RetailerBrandsFiltered?postcode={0}&countryCode={1}", model.Postcode, model.SelectedCountry);

     // Create the request to call the external mvc controller to retrieve the retailers
     var req = (HttpWebRequest)WebRequest.Create(url);
     req.Method = "GET";
     req.ContentType = "xml";

     // Do the request to external controller
     var xDoc = XDocument.Load(req.GetResponse().GetResponseStream());

     // Get some nodes
     var items = xDoc.Descendants("item");

     foreach(var item in items)
     {
         string urn = item.Element("URN").Single().Value;
         // Do more stuff
     }

 }
 catch (Exception ex)
 {
     Console.WriteLine(ex);
 }

Se MSDN article和此Stack Overflow question了解详情。