3

i want to deserialize a xml-string to an object using XmlSerializer.
The xml-string contains additional unknown nodes, which are not covered by my object-class i want to deserialize to. After deserialization, fields before the unknown node are filled ("ast"), but all fields after it ("pfosten" not in object-class) remain empty.

xml-string:

<Baum>
   <ast>1</ast>
   <pfosten>2</pfosten>
   <wurzel>3</wurzel>
   <blatt>4</blatt>
</Baum>

object-class:

[Serializable]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public class Baum
{
    public Baum() { }
    string _ast;
    string _wurzel;
    string _blatt;
    [System.Xml.Serialization.XmlElementAttribute(DataType = "NCName", Order = 0)]
    public string ast
    {

        get { return _ast; }

        set { _ast = value; }

    }
    [System.Xml.Serialization.XmlElementAttribute(DataType = "NCName", Order = 1)]
    public string wurzel
    {

        get { return _wurzel; }

        set { _wurzel = value; }

    }
     [System.Xml.Serialization.XmlElementAttribute(DataType = "NCName", Order = 2)]
    public string blatt
    {

        get { return _blatt; }

        set { _blatt = value; }

    }
}

my code looks like that:

private object DeserializeString(Type t, string s)
{
    object obj;
    XmlSerializer serializer = new XmlSerializer(t);
    serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);

    using (var reader = new StringReader(s))
    {
        obj = serializer.Deserialize(reader);
    }
    return (obj);
}
private void serializer_UnknownNode(object sender, XmlNodeEventArgs e)
{
    Debug.WriteLine("UnknownNode Name: {0}", e.Name);
}

During debug i can see, that the serializer_UnknownNode() method is called on "pfosten" and also for each following node.

I program against .Net 2.0.

Hope i provided all information and that someone can help me with this!
thanks a lot, monk

hc2p
  • 188
  • 1
  • 11

1 Answers1

2

Is the order of evaluation relevant?

If not, remove the Order parameter from the XmlElementAttribute on all properties, and it will deserialize fine, i.e.:

[System.Xml.Serialization.XmlElementAttribute(DataType = "NCName")]
public string blatt
{

    get { return _blatt; }

    set { _blatt = value; }

}
Willem van Rumpt
  • 6,490
  • 2
  • 32
  • 44
  • Exactly! If there is an unknown node, it shifts all the following elements by one position, and XmlSerializer doesn't recognize them anymore because they're not at the expected position. +1 – Thomas Levesque Jan 15 '11 at 23:11
  • thanks a lot! the attributes were set by xsd2code-plugin and i never thought about it! makes totally sense. (would like to vote u up, but i cant) – hc2p Jan 16 '11 at 01:49