1

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?

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Simon
  • 1,955
  • 5
  • 35
  • 49

1 Answers1

1

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

Community
  • 1
  • 1
Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
  • I can't move order attribute. How can I add than node2 to my class definition and since I don't know it's type(it is array with sub elements of unknown type), just use as object type.Something like: [DataMember] [XmlIgnore("Node2", Order = 20)] public Object[] Node2 { get; set; } – Simon Jan 16 '17 at 14:00
  • I think, you could just add it as [XmlElement("Node2", Order = 15)] public object Node2 { get; set; } with your simple xml it works. – Maksim Simkin Jan 16 '17 at 14:04
  • @Simon Why can't you remove the order attributes? That's what's preventing this from working. I can't see they're doing anything that helps you. – Charles Mager Jan 16 '17 at 14:55
  • Thanks. I have added all missing nodes to class definition and now it works. Order attribute is there probably for some reason(it is not my code). So, it is better to leave it there. – Simon Jan 17 '17 at 07:22