Sto avendo problemi a provare a deserializzare alcuni XML e speravo che qualcuno potesse offrire assistenza. Ho letto molti post simili ma non riesco a risolvere questo problema.
XML Sto tentando di deserializzare
xxxxx fghgh [email protected] 120 The password is invalid
Classe che sto cercando di deserializzare in:
[Serializable, XmlRoot(ElementName = "register-account", Namespace = "MyNamespace")] [XmlType("register-account")] public class RegisterAccountResponse { [XmlAttribute("success")] public bool Success { get; set; } /// /// Gets or sets the Tennant email address /// [XmlElement("email")] public string Email { get; set; } /// /// Gets or sets the tennant password /// [XmlElement("password")] public string Password { get; set; } /// /// Gets or sets the Tennant username /// [XmlElement("user-name")] public string Username { get; set; } /// /// A Tenant Portal error relating to the RegisterAccountRequest /// [XmlElement("error")] public QubeError Error; }
Metodo di deserializzazione
public static T Deserialize(string data) where T : class { if (data == null) { return null; } if (data.Trim().Length == 0) { return null; } var ser = new XmlSerializer(typeof(T)); using (var sr = new StringReader(data)) { return (T)ser.Deserialize(sr); } }
Chiamata al metodo di deserializzazione
var data = Helper.Deserialize(xml);
Eccezione:
C’è un errore nel documento XML (1, 2). —> System.InvalidOperationException: non era previsto. su Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderData.Read5_data ()
Eccezione interna come segue:
was not expected.
Decolla semplicemente il Namespace =
:
[XmlRoot("register-account"), XmlType("register-account")] public class RegisterAccountResponse {...}
dal momento che il tuo xml non sembra essere in uno spazio dei nomi xml. Inoltre, [Serializable]
non è utilizzato da XmlSerializer
.
Se il tuo xml stava usando un namespace avrebbe un xmlns
alla radice.
Inoltre, per aiutare con i chiamanti è ansible aggiungere where T : class, new()
(il , new()
è l’aggiunta) al metodo Deserialize
, poiché XmlSerializer
richiede un costruttore XmlSerializer
pubblico.
Ho trovato il seguente problema risolto per me
if (elem.Attribute(XNamespace.Xmlns + "xsi") == null) { elem.Add(new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance")); } if (elem.Attribute(XNamespace.Xmlns + "xsd") == null) { elem.Add(new XAttribute(XNamespace.Xmlns + "xsd", "http://www.w3.org/2001/XMLSchema")); }