简体   繁体   中英

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

I'm trying to deserialize the following XML response into ac# 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>

Try making your class

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

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

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