简体   繁体   中英

C# XML Deserialize xmlns

My code:

CampaignList myObject;
XmlSerializer mySerializer = new XmlSerializer(typeof(CampaignList));
**myObject = (CampaignList)mySerializer.Deserialize(xmlDoc.CreateReader());**

Error:

<CampaignListXml xmlns='api.paycento.com/1.0'> werd niet verwacht.
 [InvalidOperationException: <CampaignListXml
 xmlns='api.paycento.com/1.0'> werd niet verwacht.]   
 Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderCampaignList.Read4_CampaignListXml()
 +214

The xml response:

<CampaignListXml xmlns="api.paycento.com/1.0" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Allcampaign>
</Allcampaign>
</CampaignListXml>

I've tried adding the encoding parameter to the Deserialize method, but it gives an error "UTF8 not supported for XMLSerializer". I tried UTF8, UTF-8 and System.Text.Encoding.UTF8.EncodingName;

Here is the entire code, if you want to follow it.

    public IEnumerable<Campaign> GetCampaigns()
    {
        return GetCampaigns("active", 0, 50, "", "");
    }
    public IEnumerable<Campaign> GetCampaigns(string status, int startIndex, int pageSize, string orderby, string sort)
    {
        return GetCampaigns(status, startIndex, pageSize, orderby, sort, SessionKey);
    }
    public IEnumerable<Campaign> GetCampaigns(string status, int startIndex, int pageSize, string orderby, string sort, string sessionKey)
    {
        if (string.IsNullOrEmpty(sessionKey) || sessionKey.Length != 34)
            throw new ArgumentException("Session key must be 34 chars long. " + sessionKey.Length);
        string suffix = String.Format("campaigns/all/?status={0}&start={1}&psize={2}&orderby={3}&sort={4}&session={5}", status, startIndex, pageSize, orderby, sort, sessionKey);
        string uri = BASE_URL + suffix;
        string response = PerformAndReadHttpRequest(uri, "GET", "");
        string xml = "<CampaignListXml " + response.Substring(response.IndexOf('>'));      
        CampaignList myObject;
          XmlReaderSettings settings = new XmlReaderSettings();
          using (StringReader textReader = new StringReader(xml))
          {
              using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
              {
                  XmlSerializer mySerializer = new XmlSerializer(typeof(CampaignList));
                  myObject = (CampaignList)mySerializer.Deserialize(xmlReader);
              }
          }
        return myObject.Campaign;
    }
    #endregion
    #region util methods
    private HttpWebResponse DoHttpWebRequest(String uri, String method, string data)
    {
        HttpWebRequest req = WebRequest.Create(uri) as HttpWebRequest;
        req.KeepAlive = false;
        req.ContentType = "application/xml";
        req.Method = method;
        if ((method.Equals("POST") || method.Equals("PUT")) && data != null)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            Stream PostData = req.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
        }
        return req.GetResponse() as HttpWebResponse;
    }
    private string ReadHttpResponse(HttpWebResponse response)
    {
        Encoding enc = System.Text.Encoding.UTF8;
        StreamReader loResponseStream = new StreamReader(response.GetResponseStream(), enc);
        string returnVal = loResponseStream.ReadToEnd();
        loResponseStream.Close();
        response.Close();
        return returnVal;
    }
    private string PerformAndReadHttpRequest(String uri, String method, string data)
    {
        return ReadHttpResponse(DoHttpWebRequest(uri, method, data));
    }

Your CompaignList class should be decorated with XmlRootAttribute as below

[XmlRoot("CampaignListXml", Namespace = "api.paycento.com/1.0")]
public class CampaignList
{
}

Then you can deserialize it from xml as below

using (StringReader reader = new StringReader(xml))
{
    XmlSerializer serializer = new XmlSerializer(typeof(CampaignList));
    CampaignList x1 = serializer.Deserialize(reader) as CampaignList;
}

Use this:

    XmlReaderSettings settings = new XmlReaderSettings();
    using (StringReader textReader = new StringReader(xml))
    {
       using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
       {
         myObject =(CampaingList)mySerializer.Deserialize(xmlReader);
       }
    }

This way you deserialize directly the xml string, with an intermediate text reader.

The usings are there to close/dispose the streams when you no longer need them. You can rewrite it explicitly if you feel more comfortable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM