0

您好,我正在学习这些东西,我需要向站点发送请求以获取 xml 作为响应,而不是对其进行反序列化并查看其中的任何内容...我创建了请求反序列化方法和流方法以及 Xml Schema,但现在我不知道接下来会发生什么不工作,所以如果有人知道一些不错的教程,请给我链接。

public static class LoadXml
{
    public static root material;



    public static void LoadXML()
    {
        var serviceUrl = "http://api.deezer.com/2.0/artist/27&output=xml";
        string serviceName = "Deezer";

        HttpWebRequest request = null;
        WebResponse response = null;

        request = WebRequest.Create(serviceUrl) as HttpWebRequest;
        request.Method = "GET";
        request.ContentType = " text/xml";



        material = Deserialize<root>(GetResponseStream(request, response, serviceName));

        Console.WriteLine(material.ToString());
    }

    public static T Deserialize<T>(MemoryStream stream)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        T result = (T)serializer.Deserialize(stream);

        return result;
    }

    public static MemoryStream GetResponseStream(HttpWebRequest request, WebResponse response, string debugServiceName)
    {

        response = request.GetResponse();

        MemoryStream stream = new MemoryStream();
        response.GetResponseStream().CopyTo(stream);
        stream.Position = 0;

        return stream;
    }

}
4

1 回答 1

1

Place (or load) the results into an [XDocument][1] and work with it from there by manipulating and extracting data from the document.

Using the url as a starting point this is a snippet (easier way to load; try it) where we load it and then look at a target child node if the structure returned was (\root\name):

XDocument doc = XDocument.Load(@"http://api.deezer.com/2.0/artist/27&output=xml");

Console.WriteLine ( doc.ToString() );

/*
<root>
  <id><![CDATA[27]]></id>
  <name><![CDATA[Daft Punk]]></name>
  <link><![CDATA[http://www.deezer.com/artist/27]]></link>
  <picture><![CDATA[http://api.deezer.com/2.0/artist/27/image]]></picture>
  <nb_album><![CDATA[54]]></nb_album>
  <nb_fan><![CDATA[592180]]></nb_fan>
  <radio><![CDATA[1]]></radio>
  <type><![CDATA[artist]]></type>
*/

Console.WriteLine ( doc.Element("root").Element("name").Value);
// Outputs:
// Daft Punk

Update Alternate Load (Parse)

var xml = @"
<root>
  <id><![CDATA[27]]></id>
  <name><![CDATA[Daft Punk]]></name>
  <link><![CDATA[http://www.deezer.com/artist/27]]></link>
  <picture><![CDATA[http://api.deezer.com/2.0/artist/27/image]]></picture>
  <nb_album><![CDATA[54]]></nb_album>
  <nb_fan><![CDATA[592180]]></nb_fan>
  <radio><![CDATA[1]]></radio>
  <type><![CDATA[artist]]></type>
</root>";

var doc = XDocument.Parse( xml );

Console.WriteLine ( doc.Element("root").Element("name").Value);
// Outputs
// Daft Punk
于 2013-01-03T19:43:13.413 回答