Share via

Deserialize Trivial XML

Julio Bello 221 Reputation points
2023-08-11T20:50:49.1866667+00:00

Hi, Everybody!...

All I need to do is to deserialize the following, seemingly trivial XML...

<ExtendedProperties> <ExtendedProperty> <Property>Some Property</Property> <Value>Some Value</Value> </ExtendedProperty> <ExtendedProperty> <Property>Some Other Property</Property> <Value>Some Other Value</Value> </ExtendedProperty> </ExtendedProperties>

I wrote the following code...

private ExtendedProperties XmlStringToObject(string xmlString)
{
	using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
	{
		var xmlSerializer = new XmlSerializer(typeof(ExtendedProperties));

		return (ExtendedProperties)xmlSerializer.Deserialize(memoryStream);
	}
}
  • Where ExtendedProperties is simply a List of ExtendedProperty and ExtendedProperty is simply a Property/Value pair.
public class ExtendedProperties : List<ExtendedProperty>
{
	***<SNIP />***
}
public class ExtendedProperty
{
	public string Property { get; set; }
	public string Value { get; set; }

	***<SNIP />***
}

I am getting the following error...

System.InvalidOperationException: <ExtendedProperties xmlns=''> was not expected.

What am I doing wrong?

Developer technologies | .NET | .NET Runtime
Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

P a u l 10,766 Reputation points
2023-08-11T21:37:57.74+00:00

You just need to decorate your root type to tell the serialiser what the root node is in your XML:

[XmlRoot("ExtendedProperties")]
public class ExtendedProperties : List<ExtendedProperty> {
}

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.