Rod Johnson
Rod Johnson

Reputation: 2427

Deserializing XML in C# when there is just a single element

I'm trying to deserialize the following XML response into a c# object

  <?xml version="1.0" encoding="utf-8"?>
  <string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
     Error message
  </string>

Here is the object I'm trying to deserialize to. Not quite sure how to make the root element match the ErrorMessage property

[Serializable]
public class QObject
{
    [XmlElement("string")]
    public string ErrorMessage { get; set; }
}

When I serialize a QObject into a string, it looks like this

    <?xml version="1.0" encoding="utf-16"?>
<QObject xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><string>test</string></QObject>

Upvotes: 1

Views: 878

Answers (1)

&#208;аn
&#208;аn

Reputation: 10875

Try making your class

[XmlRoot("string")]
public class QObject
{
    [XmlText]
    public string ErrorMessage { get; set; }
}

The [XmlText] attribute is described here and [XmlRoot] here.

Upvotes: 2

Related Questions