sylvanaar
sylvanaar

Reputation: 8216

How to use .NET XML serialization without a guaranteed schema

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>

Upvotes: 1

Views: 334

Answers (1)

Joe Field
Joe Field

Reputation: 416

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

Upvotes: 1

Related Questions