1

我尝试反序列化以下 xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<common:messages xmlns:xlink="http://www.w3.org/1999/xlink" 
                 xmlns:ns3="http://rest.immobilienscout24.de/schema/platform/gis/1.0" 
                 xmlns:common="http://rest.immobilienscout24.de/schema/common/1.0">
  <message>
    <messageCode>ERROR_DESCRIPTION</messageCode>
    <message>The request is not schema valid. [MESSAGE: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 3; cvc-complex-type.2.4.a: Invalid content was found starting with element 'external-Id'. One of '{externalId, title}' is expected.] </message>
  </message>
  <message>
      ...
  </message>
</common:messages>

进入以下messages类实例:

[XmlRoot("messages", Namespace = NS.Common)]
public partial class messages
{
    [XmlElementAttribute("message")]
    public List<Message> message { get; set;}
}

public partial class Message
{
    [XmlElement("messageCode", Namespace = NS.Common)]
    public MessageCode messageCode { get; set; }

    [XmlElement("message", Namespace = NS.Common)]
    public string message { get; set; }
}

[Serializable]
[XmlType(Namespace = NS.Common)]
public enum MessageCode
{
    ERROR_DESCRIPTION,
    RESOURCE_CREATED
}


public class NS
{
    public const string Common = "http://rest.immobilienscout24.de/schema/common/1.0";
}

public class XmlHelper
{
    public static T Deserialize<T>(string xml, Encoding encoding = null) where T : new()
    {
            if (xml == string.Empty)
                return new T();

            var serializer = new XmlSerializer(typeof(T));
            encoding = encoding ?? Encoding.UTF8;
            using (var stream = new MemoryStream(encoding.GetBytes(xml)))
                return (T)serializer.Deserialize(stream);
    }
}

我从 XmlSerializer 中没有收到任何错误,但消息集合始终为空。

我怀疑 XmlSerializer 无法正确解析什么是“消息”——数组项或包含字符串消息的元素。我无法更改 xml 结构,因此我必须修复我的反序列化程序或一些 xml 属性属性。

我的代码有什么问题?任何帮助表示赞赏。

4

1 回答 1

0

我猜你的问题是命名空间。由于消息似乎是唯一带有公共命名空间的元素,您可以尝试为所有子元素重置命名空间。像这样的东西:

[XmlRoot("messages", Namespace = NS.Common)]
public partial class messages
{
    [XmlElementAttribute("message", Namespace = "")]
    public List<Message> message { get; set;}
}

public partial class Message
{
    [XmlElement("messageCode", Namespace = "")]
    public MessageCode messageCode { get; set; }

    [XmlElement("message", Namespace = "")]
    public string message { get; set; }
}

[Serializable]
[XmlType(Namespace = "")]
public enum MessageCode
{
    ERROR_DESCRIPTION,
    RESOURCE_CREATED
}

或与Form = System.Xml.Schema.XmlSchemaForm.Unqualified

于 2013-09-23T09:36:08.763 回答