Giulio Ladu
Giulio Ladu

Reputation: 192

Why Can't I Deserialize This xml?

I am currently trying to deserialize some XML in the following format:

<content:encoded>![CDATA[...

And I have an object which has a property which looks like:

[XmlElementAttribute("content")]
public string Content { get; set; }

However despite the XML always having a value the property in the code is always null?

Upvotes: 0

Views: 250

Answers (2)

jheddings
jheddings

Reputation: 27563

content is a namespace in your example. Your element name is actually encoded so you will need to use the attribute marking your property as such:

[XmlElement("encoded", Namespace => "custom-content-namespace")]
public string Content { get; set; }

Note that you will need to declare the namespace in your containing XML:

<content:encoded xmlns:content="custom-content-namespace">![CDATA[...

This also means any child nodes would be prefixed with the same namespace. Not so much an issue for CDATA content, but just in case you have other elements you are trying to deserialize.

For a related questions to this, see Deserializing child nodes outside of parent's namespace using XmlSerializer.Deserialize() in C#

Upvotes: 3

D Stanley
D Stanley

Reputation: 152556

content is the namespace - encoded is the element name. So your XmlElementAttribute should be:

[XmlElement(Name="encoded", Namespace="<whatever namespace 'content' refers to in your XML>")]
public string Content { get; set; }

Upvotes: 3

Related Questions