-
Notifications
You must be signed in to change notification settings - Fork 0
Home
[As of April 2025 this Wiki is currently being written, expect a few exposed cables here and there]
MapXML is a lightweight .NET library designed for bidirectional mapping and transformation between XML structures and strongly-typed C# objects. It provides a framework for defining XML structure, resolving types, and performing automated parsing and object instantiation.
To use MapXML in your project you can either install through NuGet
dotnet add package MapXML
or clone and compile along with your project :
git clone https://github.com/LongJSilver/MapXML.git
MapXML is not meant to handle all kinds of XML structure, it focuses instead on XML structures that closely resemble the CLR object models they need to be mapped to. The most efficient use of the library involves annotations through member attributes and very little (or zero) mapping code written.
<Movies Owner="Alice" >
<Movie Title="The Fellowship of the Ring" Director="Peter Jackson" ReleaseYear="2001" Genre="Fantasy" />
<Movie Title="The Two Towers" Director="Peter Jackson" ReleaseYear="2002" Genre="Fantasy" Prequel="The Fellowship of the Ring" />
<Movie Title="The Return of the King" Director="Peter Jackson" ReleaseYear="2003" Genre="Fantasy" Prequel="The Two Towers" />
</Movies>
public class MovieCollection
{
[XMLChild("Movie")]
public List<Movie> Movies { get; set; } = new List<Movie>();
[XMLAttribute("Owner")]
public string OwnerName { get; set; }
//Lookup function to help MapXML lookup previously loaded Movies by title
[XMLFunction]
public Movie? GetMovie([XMLParameter("Title")] string t)
{
return Movies.FirstOrDefault(m => m.Title == t);
}
}
public class Movie
{
public string Title { get; set; }
public string Director { get; set; }
public int ReleaseYear { get; set; }
public string Genre { get; set; }
[XMLAttribute("Prequel", DeserializationPolicy.Lookup)]
public Movie Prequel { get; set; }
}
static void Main(string[] args)
{
//Define options
IDeserializationOptions opt =
XMLDeserializer.OptionsBuilder()
.AllowImplicitFields(true) //<-- Allow implicit fields
.Build();
MovieCollection movies = new MovieCollection(); //This will be the owner of the root node
// Create an instance of the XMLDeserializer
XMLDeserializer deserializer = new XMLDeserializer(MovieCollectionSample.XML, Handler: null, RootNodeOwner: movies, Options: opt);
deserializer.Run();
// Inspect the results
Console.WriteLine(movies.OwnerName);
Console.WriteLine(movies.Movies.Count);
}