3

So I'm working with some XML files that I believe are most likely badly formed, and I'm trying to figure out how and if I can use the XmlSerializer to deserialize this XML into a logical business object. Let's say I have the following XML file:

<Root>
   <ArrayType1 Name="Bob"/>
   <ArrayType1 Name="Jim"/>
   <ArrayType2 Name="Frank">
      <SubItem Value="4"/>
   </ArrayType2>
   <ArrayType2 Name="Jimbo">
      <SubItem Value="2"/>
   </ArrayType2>
</Root>

Now I'd like to create a class that has these three types, Root, ArrayType1 and ArrayType2, but I'd like to get two lists in Root, one containing a collection of ArrayType1 items, and one containing a collection of ArrayType2 items, but it seems that these items need to have some sort of root, for example, I know how to deserialize the following just fine:

<Root>
   <ArrayType1Collection>
      <ArrayType1 Name="Bob"/>
      <ArrayType1 Name="Jim"/>
   </ArrayType1Collection>
   <ArrayType2Collection>
      <ArrayType2 Name="Frank">
         <SubItem Value="4"/>
      </ArrayType2>
      <ArrayType2 Name="Jimbo">
         <SubItem Value="2"/>
      </ArrayType2>
   </ArrayType2Collection>
</Root>

But how would I deserialize this without the parent ArrayType#Collection elements surrounding the ArrayType# elements?

Will the XML Serializer even allow this at all?

1 Answer 1

11

Isn't that just:

[Serializable]
public class Root {
    [XmlElement("ArrayType1")]
    public List<ArrayType1> ArrayType1 {get;set;}

    [XmlElement("ArrayType2")]
    public List<ArrayType2> ArrayType2 {get;set;}
}

?

Alternatively, just put the xml into a file ("foo.xml") and use:

xsd foo.xml
xsd foo.xsd /classes

and look at the generated foo.cs

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

3 Comments

Overcomplicating again... Thanks. :)
Are the XmlElements here supposed to read, e.g., ArrayType1 or ArrayType1Collection?
When I look the OP's second XML snippet, I see an XmlElement with the name ArrayType1Collection that is essentially a set of XmlElements of type ArrayType1. When I look at your code snippet, I see an XmlElement with the name ArrayType1 that is essentially a set of objects of type ArrayType1. I would expect the name of the XmlElement to be ArrayType1Collection (since that is the name of the element that contains children of type ArrayType1).

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.