【问题标题】:Deserialise an xml representation of a string and primitive type - ASP.NET Web API反序列化字符串和原始类型的 xml 表示 - ASP.NET Web API
【发布时间】:2012-10-07 21:54:27
【问题描述】:

我目前正在使用 ASP.net Web API 实现一个 Web 服务,我的一个方法返回一个字符串。问题是它返回这样的字符串:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization">Some Resource</string>

这种响应是我想要的,但我不知道如何在我的网络服务客户端中反序列化它。

您将如何反序列化表示字符串或任何原始数据类型的任何 xml?

谢谢!

【问题讨论】:

    标签: c# xml serialization xml-serialization asp.net-web-api


    【解决方案1】:

    您可以使用 System.Net.Http.Formatting.dll 中的 ReadAsAsync。说 'uri' 会给我这些数据:

    <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
      Some Resource
    </string>
    

    然后你可以使用ReadAsAsync来获取XML中的字符串:

            HttpClient client = new HttpClient();
            var resp = client.GetAsync(uri).Result;
            string value = resp.Content.ReadAsAsync<string>().Result;
    

    (我这里直接调用.Result来演示ReadAsAsync的使用...)

    【讨论】:

      【解决方案2】:
      // Convert the raw data into a Stream
      string rawData = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Some Resource</string>";
      MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(rawData)); 
      
      // User DataContractSerializer to deserialize it
      DataContractSerializer serializer = new DataContractSerializer(typeof(string));
      string data = (string)serializer.ReadObject(stream);
      
      Console.WriteLine(data);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-11
        相关资源
        最近更新 更多