Question

Basically, I have some xml I need to deserialize. At the time I write my code, I'll know the structure of the XML, but I'd like to be able to make simple changes to the xml without having to update the serialization code.

Example:

<foo>
  <bar/>
</foo>

I'd like to be able to deserialize foo, even if i add an additional node which is not defined in the attibuted serializable class.

<foo>
  <bar/>
  <extra-tag/>
</foo>
Was it helpful?

Solution

If I understand your question correctly this should work fine.

Given a class:

[XmlRoot("foo")]
public class Foo
{
    [XmlElement("bar")]
    public string Bar;
    [XmlElement("extra-tag")]
    public string ExtraTag;
}

Then this code works fine:

string xml = 
@"<foo>
  <bar>bar</bar>
  <extra-tag>extra-tag</extra-tag>
</foo>";


XmlSerializer serializer = new XmlSerializer(typeof(Foo));
Foo afoo = (Foo)serializer.Deserialize(new StringReader(xml));

But if your class looks like this:

[XmlRoot("foo")]
public class Foo
{
    [XmlElement("bar")]
    public string Bar;
}

the code continues to work

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top