1

I have the following xml file:

<ArrayOfX xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <X>
    <Name>Name1</Name>
    <ArrayOfY>
      <Y>
        <Member1>1</Member1>
      </Y>
      ...
    </ArrayOfY>
  </X>
  ...
</ArrayOfX>

public class X {
    public string Name { get; set; }
    public List<Y> Y { get; set; }
}

public class Y {
    public String Member1 { get; set; }
}

But if i try to deserialize with XmlSerializer, Name contains the correct value but the Y list is empty. Any idea?

XmlSerializer serializer = new XmlSerializer( typeof( List<X> ) );
return (List<X>)serializer.Deserialize(reader);
0

2 Answers 2

1

Try this:

public class X {
    public string Name { get; set; }
    [XmlArray(ElementName = "ArrayOfY")]
    public List<Y> Y { get; set; }
}

With you class definition, if you try to serialize of a List<X>, the output would looks like:

<ArrayOfX xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <X>
    <Name>Name1</Name>
    <Y> <!-- Not ArrayOfY -->
      <Y>
        <Member1>1</Member1>
      </Y>
      ...
    </Y>
  </X>
  ...
</ArrayOfX>

Your provided xml file is not a valid format to the XmlSerializer(typeof(List<X>)). It's expecting <Y> instead of <ArrayOfY> for the List<Y> member of X.

The attribute I added would instruct the serializer to look for an element with name ArrayOfY instead.

Sign up to request clarification or add additional context in comments.

Comments

1

You will need to populate the 'extraTypes' array parameter with typeof(Y).

See http://msdn.microsoft.com/en-us/library/e5aakyae.aspx

1 Comment

I've already tried it: XmlSerializer serializer = new XmlSerializer( typeof( List<X> ), new Type[] { typeof( Y ), typeof( List<Y> ) } );, but does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.