Simon
Simon

Reputation: 2035

Deserialize XML to object and ignore some nodes

I have XML string with nodes:

MyXmlString="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><MyNodes><Node1 /><Node2 /><Node3 /></MyNodes>";

And I have class:

public class MyClass
{
    [DataMember]
    [XmlElement("Node1", Order = 10)]
    public String Node1 { get; set; }

    [DataMember]
    [XmlElement("Node3", Order = 20)]
    public String Node3 { get; set; }
}

When I deserialize from XML to object, I would like to skip Node2 inside string:

MyClass MyObject= XElement.Parse(MyXmlString).FromXml<MyClass>();

MyObject has value for Node1, but Node3 is null, even when xmlString has value for it. I can use xmlIgnore when serializing some object to Xml. But my case is opposite - xml has nodes which I don't need. What would be the easiest way to do this?

Upvotes: 1

Views: 2982

Answers (1)

Maksim Simkin
Maksim Simkin

Reputation: 9679

If you remove your Order attribute, you will get values for Node3, XmlSerializer will just ignore Node2. If you don't really need ordering you shouldn't use it.

Look here for very similar case: XmlSerializer. Skip xml unknown node

Upvotes: 1

Related Questions