Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# deserialize xml array of different types into multiple arrays

I have the following xml:

<Applications>
    <AccessibleApplication></AccessibleApplication>
    <AccessibleApplication></AccessibleApplication>
    <EligibleApplication></EligibleApplication>
    <EligibleApplication></EligibleApplication>
</Applications>

Is there a way to deserialize this into a C# object so that the AccessibleApplications and EligibleApplications are two separate arrays? I tried the following but get an exception because "Applications" is used more than once.

[XmlArray("Applications")]
[XmlArrayItem("AccessibleApplication")]
public List<Application> AccessibleApplications { get; set; }

[XmlArray("Applications")]
[XmlArrayItem("EligibleApplication")]
public List<Application> EligibleApplications { get; set; }

The exception is: The XML element 'Applications' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.

Is this possible to do?

Thanks!

Edit: I forgot to mention that I do not want to have an "Applications" class just for the sake of providing a container object for the two arrays. I have several situations like this and I don't want the clutter of these classes whose only purpose is to split up two arrays of the same type.

I was hoping to be able to deserialize the two arrays into an outer object using some sort of tag like [XmlArrayItem="Application/AccessibleApplication"] without creating an "Applications" class.

like image 437
Bumper Avatar asked Nov 21 '22 16:11

Bumper


1 Answers

I've found a fairly neat way to do this, first make a class like this:

using System.Xml.Serialization;

[XmlRoot]
public class Applications
{
    [XmlElement]
    public string[] AccessibleApplication;
    [XmlElement]
    public string[] EligibleApplication;
}

Notice how the elements are individual arrays. Now using this class (I had my XML in a separate file hence the XmlDocument class).

var doc = new XmlDocument();
doc.Load("../../Apps.xml");
var serializer = new XmlSerializer(typeof(Applications));
Applications result;

using (TextReader reader = new StringReader(doc.InnerXml))
{
    result = (Applications)serializer.Deserialize(reader);
}

Now to prove this works you can write this all in to a console app and do a foreach to print all the values in your arrays, like so:

foreach (var app in result.AccessibleApplication)
{
    Console.WriteLine(app);
}
foreach (var app in result.EligibleApplication)
{
    Console.WriteLine(app);
}
like image 71
hevans900 Avatar answered Nov 23 '22 05:11

hevans900