2017-08-17 208 views
-3

如何直接从主机上的xml文件获取项目列表? 更确切地说,我想这xml文件http://gamerpro.webd.pl/data/modlist.xml我拿出的项目清单,并听取了代码从URL获取Xml数据

If (! File.Exists ("received list of items")) 
{ 
Await client.DownloadFileTaskAsync (new Uri (url + "received item list"), dir + "received item list"); 
} 

回答

0
using System; 
using System.Xml; 

namespace ReadXMLfromURL 
{ 
    /// <summary> 
    /// Summary description for Class1. 
    /// </summary> 
    class Class1 
    { 
     static void Main(string[] args) 
     { 
      String URLString = "http://localhost/books.xml"; 
      XmlTextReader reader = new XmlTextReader (URLString); 

      while (reader.Read()) 
      { 
       switch (reader.NodeType) 
       { 
        case XmlNodeType.Element: // The node is an element. 
         Console.Write("<" + reader.Name); 

         while (reader.MoveToNextAttribute()) // Read the attributes. 
          Console.Write(" " + reader.Name + "='" + reader.Value + "'"); 
         Console.Write(">"); 
         Console.WriteLine(">"); 
         break; 
        case XmlNodeType.Text: //Display the text in each element. 
         Console.WriteLine (reader.Value); 
         break; 
        case XmlNodeType. EndElement: //Display the end of the element. 
         Console.Write("</" + reader.Name); 
         Console.WriteLine(">"); 
         break; 
       } 
      } 
     } 
    } 
} 
0

你可以做这样的事情

// Make your request 
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestURL); 
request.Headers.Add("Accept", "application/xml"); 
HttpResponseMessage response = client.SendAsync(request).Result; 

// Parse your response 
if (response.IsSuccessStatusCode) 
{ 
    using (Stream httpResponseStream = response.Content.ReadAsStreamAsync().Result) 
    { 
     XDocument responseXML = XDocument.Load(httpResponseStream); 

     // My Chosen element is the element you're looking for 
     IEnumerable<XElement> myElements = responseXML.Root.Elements("MyChosenElement"); 

     foreach (XElement myEl in myElements) 
     { 
      // Access each element like this myEl.Child 
      // Do what you'd like with it 
     } 
    } 
}